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();
No, you can't downcast anything in C#. A
Dog
is anAnimal
, but not everyAnimal
is aDog
.If you want to be able to cast a
List<Foo>
toFooCollection
, you'll need to add an implicit or explicit conversion from the former in the latter. Or add a constructor with a parameterIEnumerable<Foo>
and callbase(IEnumerable<T> items)
with that parameter.You shouldn't inherit
List<T>
anyway.Anyway try searching, see duplicate.