Asad Butt Asad Butt - 11 months ago 80
C# Question

Convert List<DerivedClass> to List<BaseClass>

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?

Answer Source

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();