Search code examples
c#listinheritancecollectionscovariance

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?


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