Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast generic list form DerivedClass to BaseClass

Tags:

c#

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?

like image 404
lwanda Avatar asked Feb 04 '26 07:02

lwanda


1 Answers

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>.

like image 170
JMP Avatar answered Feb 13 '26 10:02

JMP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!