generic list and casting

Posted on 2008-11-14
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
    LVL 7

    Accepted Solution

    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

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    In my previous article ( we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
    A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    755 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

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now