Convert List<DerivedClass> to List<BaseClass>

c#, collections, covariance, inheritance, list

Solution

The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:

List<A> listOfA = new List<C>().ConvertAll(x => (A)x);

You could also use Linq:

List<A> listOfA = new List<C>().Cast<A>().ToList();

Problem

While we can inherit from base class/interface, why can't we declare a `List<>` using same class/interface? ``` interface A { } class B : A { } class C : B { } class Test { static void Main(string[] args) { A a = new C(); // OK List<A> listOfA = new List<C>(); // compiler Error } } ``` Is there a way around?

Original source

Related problems