1

I have this example class:

class MyClass
{
   public string name;
   public string name2;
}

and I want to make a list of MyClass like List<MyClass> myClass = new List<MyClass>(); but I was told that a better approach would be to make some kind of a "Collection". This is how my List looks like now:

class MyClassCollection : List<MyClass>
{

}

As I understand it is better because I can now use my own methods and for example override .Add().

So my "By the way"-question is: Is that true?

I created MyClassCollection myClassCollection = new MyClassCollection(); and I added some MyClass objects to it. But how do I sort it by alphabetial order of name?

If it was a list I could sort it with this:

List<MyClass> myList = new List<MyClass>();
myList.Add(myClassObject1);
myList.Add(myClassObject2);
myList = myList.OrderBy(x => x.name).ToList();

But:

MyClassCollection myClassCollection = new MyClassCollection();
myClassCollection.Add(myClassObject1);
myClassCollection.Add(myClassObject2);
myClassCollection = myClassCollection.OrderBy(x => x.name).ToList();

does not work, as the ToList() method returns an object of type List<MyClass> and not a MyClassCollection object.

Fortega
  • 19,463
  • 14
  • 75
  • 113
axbeit
  • 853
  • 11
  • 35
  • You have the `List.Sort()` method at your disposal. And no, you don't have to create custom collection classes for every list/collection in your code. – dymanoid Aug 30 '19 at 13:44
  • you should not subclass from list or any other collection unless you want to add extra functionality to that classes. normaly you work directly with the generic types – Jehof Aug 30 '19 at 13:46
  • 2
    Make the class ICompare : https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icomparer-1?view=netframework-4.8 – jdweng Aug 30 '19 at 13:47
  • 5
    _So my "By the way"-question is: Is that true?_ You may have a look at [Why not inherit from List?](https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt) – Martin Backasch Aug 30 '19 at 13:48
  • 1
    Yeah, I don't know who told you to make a collection for this but its really not necessary and just hides the fact that at the end of the day its just a generic list. Its honestly worse to obfuscate this way. Anyone looking at the collection in code would assume there is special logic beyond a generic list when there isnt. – DetectivePikachu Aug 30 '19 at 13:58
  • 1
    In winforms and WPF, you'll see classes like ["ItemCollection"](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.itemcollection?view=netframework-4.8). Types for properties of UI controls have special requirements: No generics, to begin with. Use those types as an example (or just use those types) if and only if you're writing a control. – 15ee8f99-57ff-4f92-890c-b56153 Aug 30 '19 at 13:58
  • How does it "not work"? Does it not compile, does it throw an exception of does it return unexpected results? – CodeCaster Aug 30 '19 at 14:30

0 Answers0