generic list and casting

Let's say I have class A and I derive class B from class A.

class A { }

class B: class A
{ }

Then I declare variable of type List<B>.

I'm wondering why it is not possible to do cast

List<B> listB;
List<A> listA = listB as List<A>
Who is Participating?
Refael AckermannConnect With a Mentor Commented:
This is a limitation of .NET generics.
The simple explanation is you're trying to cast Lists not A or B, and List<B> is not related to List<A>.
If you're using C#3, you can do:

List<A> listA = listB.Cast<A>().ToList();

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.