I wonder why IEnumerable<int> can’t be assigned to a IEnumerable<object>. After all IEnumerable is one of the few interfaces that supports covariance…
- The subtype relation and covariance stuff works with reference types
intseems to be a proper subtype ofobject
The combination of both features doesn’t work however…
class A
{
}
class B : A
{
}
class Program
{
static void Main(string[] args)
{
bool b;
b = typeof(IEnumerable<A>).IsAssignableFrom(typeof(List<B>));
Console.WriteLine("ienumerable of ref types is covariant: " + b); //true
b = typeof(IEnumerable<object>).IsAssignableFrom(typeof(List<int>));
Console.WriteLine("ienumerable of value tpyes is covariant: " + b); //false
b = typeof(object).IsAssignableFrom(typeof(int));
Console.WriteLine("int is a subtype of object: " + b); //true
}
}
thanks for your help!
sebastian
Value types aren’t LSP-subtypes of object until they’re boxed.
Variance doesn’t work with value types. At all.
Demonstration that
intis not a proper subtype (subtype in the LSP sense) ofobject:Works:
Does not work (substitutability violated):
Returns true:
Returns false (substitutability violated):
Of course, the topic of the question (interface variance) is a third demonstration.