C #: returning an inherited class from an instance of its base class (general list)

Maybe I just remember things completely back, but I would like to know more about what I am doing wrong ...

I declared the class to be nothing more than direct inheritance from a generic list (made to simplify naming), something like this:

public class FooList : List<Foo> {} 

now in another method, completely separate from this class, I'm trying to return an instance of this class, however I want to filter the class based on the criteria, so I use the lambda expression:

 var list = new FooList(); // imagine this fills it with different items var filtered = list.FindAll(c => c.Something == "filter criteria"); 

now according to the FindAll method, it SHOULD return the list [Foo]. However, I want to return this object as a FooList, not a List [Foo]. Should I create a new instance of FooList and copy the items from the [Foo] list?

If so, why? why can't I directly convert the list to a FooList, since they are the same object?

If it CAN be done, how can I do it?

many thanks!

+4
source share
3 answers

This is not the same thing. A FooList is a List<foo> , but a List<foo> returned by the FindAll() function inherited from List<foo> is not a FooList . You will need to create a new FooList .

You can do something like create a constructor for a FooList that accepts an IEnumerable<foo> object as follows:

 class FooList : List<foo> { public FooList(IEnumerable<foo> l) : base(l) { } } 

Or you can also do something like this:

  var list = new FooList(); var filtered = list.FindAll(c => c.Something == "filter criteria"); var newList = new FooList(); newList.AddRange(filtered); return newList; 

However, as mentioned in some other answers, if you are not adding any functions, you should simply create an alias with the using keyword.

+6
source

Your problem is that you are using the wrong tool for the job. Inheritance is not a naming simplification mechanism ; Inheritance is a mechanism that is primarily intended for (1) modeling "is a kind of" relationship between classes of business domain objects "and (2) allows you to share and specialize implementation details among related types.

If you want to simplify naming, then the right tool for the job is

 using FooList = System.Collections.Generic.List<Foo>; 

at the top of each file.

+8
source

Do not declare a new FooList class. Just use an alias. At the top of the source file, write:

 using FooList = System.Collections.Generic.List<Foo>; 

Now you can write FooList everywhere and it will be considered exactly identical to List<Foo> .

+1
source

All Articles