Asad Butt Asad Butt - 1 year ago 104
C# Question

Convert List<DerivedClass> to List<BaseClass>

While we can inherit from base class/interface, why can't we declare a


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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download