SelAromDotNet
SelAromDotNet

Reputation: 4815

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

This is probably me just remembering things completely backwards, but I'd like to know more about what I'm doing wrong...

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

public class FooList : List<Foo> {}

now in another method completely separate from this class, I am trying to return an instance of this class, however I want to filter the class based on a criterion, so I'm using a 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, this SHOULD return a List[Foo]. However, I want to return this object as a FooList, not a List[Foo]. Do I have to create a new instance of FooList and copy the items from the List[Foo]?

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

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

many thanks!

Upvotes: 4

Views: 850

Answers (3)

linuxuser27
linuxuser27

Reputation: 7353

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

You could do something like create a Constructor for FooList that takes a IEnumerable<foo> object like this:

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

Or you could 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 of the other answers, if you are not adding any functionality then you should just create an alias with the using keyword.

Upvotes: 6

Timwi
Timwi

Reputation: 66584

Don’t declare a new class FooList. Just use an alias. At the top of your source file, write:

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

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

Upvotes: 1

Eric Lippert
Eric Lippert

Reputation: 660297

Your problem is that you are using the wrong tool for the job. Inheritance is not a mechanism for simplifying naming; inheritance is a mechanism primarily designed for (1) modeling "is a kind of" relationships between classes of business domain objects, and (2) enabling the sharing and specialization of implementation details amongst related types.

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

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

at the top of every file.

Upvotes: 8

Related Questions