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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With