Casting common interfaces and classes in C #

Possible duplicate:
C # covariance question

Why does the code compile in the first case, but not compile in the second?

class ClassA {

class ClassB : ClassA {

static void Main() {
    var classAList = new List<ClassA>();
    var classBList = new List<ClassB>();

    IEnumerable<ClassA> classAIEnumerable;
    IEnumerable<ClassB> classBIEnumerable = new List<ClassB>();

    // First case:
    classAIEnumerable = classBIEnumerable;

    // Second case:
    classAList = classBList;


What prevents the code from being compiled in the second case? Why can't the compiler figure out that this casting is safe?


source to share

1 answer


is not covariate because it does not define T as a type out

, unlike IEnumerable<out T>

. It also doesn't contradict, because it doesn't define T as in


If this action was allowed, you can add class C to it:

class ClassC : ClassA { 

// Second case: 
classAList = classBList; //suppose this is allowed
ClassA myC = new ClassC();
classAList.Add(myC); //Whoops! we've added a ClassC to the list which is actually a list of ClassBs



All Articles