0

I have an interface A, class B inherits from interface A. I have a list of objects:

List<B> myB;
List<A> myA;

I want to assign myB to myA but I get a error "Cannot implicit convert type 'B' to 'A':

myA = myB;

Please help me. Thanks.

Leo Vo
  • 9,980
  • 9
  • 56
  • 78
  • possible duplicate of [C# inheritance in generics question](http://stackoverflow.com/questions/4146764/c-inheritance-in-generics-question) – Binary Worrier Apr 15 '11 at 08:18

5 Answers5

1

You need to convert each element of the list. It cannot be automatically converted for you. Easiest would be Linq:

myA = myB.Cast<A>().ToList();

Update: This question: Why is this cast not possible? discusses it in more detail.

Community
  • 1
  • 1
ChrisWue
  • 18,612
  • 4
  • 58
  • 83
0

It might help you: Cast List<int> to List<string> in .NET 2.0

Community
  • 1
  • 1
Silx
  • 2,663
  • 20
  • 21
0

IList<T> is not covariant, where as IEnumerable<T> is, you can do the following..

void Main()
{

     IEnumerable<B> myB= new List<B>();
     IEnumerable<A> myA = myB;
}


public interface A
{
}

public class B :A
{
}

see this previous SO Question

Community
  • 1
  • 1
Richard Friend
  • 15,800
  • 1
  • 42
  • 60
0

You need to make a way to convert between type A and type B.

There is no way to assign a list of one type to another, unless the type B is the same as type A.

You can use the Cast<T> operator for derived types:

class A {}
class AA : A {}

List<AA> aas = new List<AA> {new AA()};
List<A> bunchofA = aas.Cast<A>().ToList();

This only works when casting to less derived types (from descendant to ancestor). This won't work:

List<A> bunchofA = new List<A> {new A()};
List<AA> aas = bunchofA.Cast<AA>.ToList();

Because the compiler cannot know what to do to make the extra bits that AA has from A.

You can also, in a rather contrived way, use implicit conversion:

class A
{
}

class B
{
    public static implicit operator B(A a)
    {
        return new B();
    }

    public static implicit operator A(B a)
    {
        return new A();
    }
}

List<B> bs = new List<B>{new B()};
List<A> bunchOfA = bs.Select(b => (A)b).ToList();

This will work in either direction, but might cause confusion, so it is better to create explicit conversion methods and use those.

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
-1

That is correct. List is a list of Apples and List is a list of .. err .. batmans! You cannot try to put one into the other.

Technically, you cannot refer to one as the other!

Jaapjan
  • 3,365
  • 21
  • 25