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?
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>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With