3

I've these two classes

public class A {}
public class B : A {}

And the cast from class A to class B works fine.

B testB1 = new B();
A testA1 = testB1;
B testB2 = (B)testA1; //this works

But: Why is this cast not working?

List<B> testB1List = new List<B>();
List<A> testA1List = ((IEnumerable<A>)testB1List).ToList();
List<B> testB2List = ((IEnumerable<B>)testA1List).ToList(); //not working

The solution is:

List<B> testB1List = new List<B>();
List<A> testA1List = ((IEnumerable<A>)testB1List).ToList();
List<B> testB2List = testA1List.Cast<B>().ToList();

But why is it like this?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
lwanda
  • 33
  • 3

1 Answers1

3

Well the Cast extension method casts each member of the list to the specified type so in your example it can then be assigned as a List<B> because all list members have been cast to B.

But in the first example, you are casting the IEnumerable itself, not the members of the list:

(IEnumerable<B>)testA1List

So it fails because it is trying to cast List<A> to IEnumerable<B>.

JMP
  • 1,864
  • 2
  • 8
  • 16