Cast generic list to inherited class

472 views Asked by At

Is it possible cast list to class which inherited list?

Example

public class FooCollection : List<Foo>
{
}

List<Foo> oFooList = new List<Foo>();
FooCollection oColl =  (FooCollecton)oFooList;

I expect that last line would work but it isn't.

PS: I will use that to cast linq result to cast inherited collection. Any help appreciated.

FooCollection oColl =  (FooCollecton)oDBClass.Where(x=> x.Id == 1).ToList();
1

There are 1 answers

0
CodeCaster On

No, you can't downcast anything in C#. A Dog is an Animal, but not every Animal is a Dog.

If you want to be able to cast a List<Foo> to FooCollection, you'll need to add an implicit or explicit conversion from the former in the latter. Or add a constructor with a parameter IEnumerable<Foo> and call base(IEnumerable<T> items) with that parameter.

You shouldn't inherit List<T> anyway.

Anyway try searching, see duplicate.