I have the following structure:
public class MyBaseClass : IGeneralClass
{
}
public class MyClass : MyBaseClass
{
...
}
public class MyDataClass
{
private List<MyClass> _data = null;
public void PopulateData()
{
...
}
public IList<IGeneralClass> Data
{
get
{
return (IList<IGeneralClass>)_data;
}
}
}
I was under the impression that I could do this in .Net4.5 because of contravariance, but when I try, I get a runtime error as follows:
Unable to cast object of type 'System.Collections.Generic.List`1[MyClass]' to type 'System.Collections.Generic.IList`1[IGeneralClass]'.
Am I casting this incorrectly, or is this not supported?
You mean covariance, contravariance is the other way around, when
A
is a subtype ofB
, thereforeX<B>
is a subtype ofX<A>
(as is the case ofAction<in T>
).IList<T>
is invariant though - notice how there's noin
orout
modifiers. You may be mistaking it forIEnumerable<out T>
, which is covariant.Why is it invariant, I hear you ask? An
IList<Dog>
cannot be treated as anIList<Animal>
, otherwise this would have to cause a runtime error: