Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidCastException from List<T> to IEnumerable<T> only in 3.5

If i call that

var list = new List<Class1>();
Test((IEnumerable<Interface1>)list);

with

public interface Interface1
{

}

public static void Test(IEnumerable<Interface1> test)
{

}

public class Class1 : Interface1
{

}

I get an InvalidCastException with the 3.5 framework, but in 4 and 4.5 it's ok. And I don't understand why, both have IEnumerable

If I check the list in 3.5 and 4.5 I can't see why I get an InvalidCastException

4.5:

public class List<T> : IList<T>, ICollection<T>, 
    IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>

3.5:

public class List<T> : IList<T>, ICollection<T>, 
    IEnumerable<T>, IList, ICollection, IEnumerable
like image 811
DarkPixel Avatar asked Dec 20 '22 04:12

DarkPixel


1 Answers

In 3.5, the IEnumerable<T> interface was not covariant. That was added in 4.0.

Covariance is required to cast to a type that is more derived, which is the case here (List<T> implements IEnumerable<T>).

MSDN

like image 152
David L Avatar answered Dec 21 '22 18:12

David L