generic list and casting

Posted on 2008-11-14
Medium Priority
Last Modified: 2012-05-05
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>
Question by:meteorrr_pcp
1 Comment

Accepted Solution

moseack earned 200 total points
ID: 22958149
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


Featured Post

Granular recovery for Microsoft Exchange

With Veeam Explorer for Microsoft Exchange you can choose the Exchange Servers and restore points you’re interested in, and Veeam Explorer will present the contents of those mailbox stores for browsing, searching and exporting.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Loops Section Overview
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question