0

Possible Duplicate:
C# variance problem: Assigning List<Derived> as List<Base>

I have a problem with list inheritance. It looks like a generic List with more specified members can't converted to a list with its base members. Look at this:

class A
{
    public int aValue {get; set;}
}

class B : A
{
    public int anotherValue {get; set;}
}

You might now expect that a List<B> is also a List<A> but that's not the case. List<A> myList = new List<B>() is not possible. Not even List<A> myList = (List<A>)new List<B>() Am I missing some basic concept here after 3 years in object oriented programming?

Community
  • 1
  • 1
MechMK1
  • 3,278
  • 7
  • 37
  • 55
  • It is just how Generics work in .NET – tcarvin Dec 10 '12 at 14:32
  • It's how covariance works in .NET for generics. You have to create an intermediate interface. I had the [same question](http://stackoverflow.com/questions/13316838/covariance-issue) a little while ago. – Candide Dec 10 '12 at 14:33

2 Answers2

6

Yup!

Assume you could do

List<A> myList = new List<B>();

Then assume you have a class

class C : A { public int aDifferentValue { get; set; } }

A C is an A, so you would expect to be able to call myList.Add(new C()) as myList thinks it is a List<A>.

But a C is not a B so a myList - which is really a List<B> - can't hold a C.


Conversely, suppose you could do

List<B> myList = new List<A>();

You can happily call myList.Add(new B()) because a B is an A.

But suppose something else stuck a C in your list (as C is an A).

Then myList[0] might return a C - which is not a B.

Rawling
  • 49,248
  • 7
  • 89
  • 127
-2

That simple conversions is not allowed For now use

List<B> lb = new List<B> { ... };
List<A> la = lb.Cast<A>().ToList();
Warr
  • 118
  • 6