abstract class A<T> {
List<T> Items { get; set; }
}
class B {}
class C : A<B> {}
class D : B {}
class E : A<D> {}
static class X {
public A<B> GetThing(bool f) {
return f ? new E() : new C();
}
}
Type of conditional expression cannot be determined because there is no implicit conversion between ‘ConsoleApplication4.E’ and ‘ConsoleApplication4.C’
Now I get the “why” (I think) but I can’t see how to make this compile. I think I have to create an interface which defines variance of some kind and inherit from that, but I’m not sure. But regardless, E() should inherit from C().
Any takers?
TIA
To use generic variance in C# you have to meet all the following conditions:
Your program meets condition 1 and condition 5 but not conditions 2, 3, or 4.
There is no way to get the variance you want because you want something that would violate condition 4. Watch what happens when we meet all the conditions except condition 4:
And a giraffe collection now contains a list of animals that contains a tiger.
You have to be typesafe if you’re going to use variance. Because the compiler cannot determine the variance annotations to be typesafe, it rejects the declaration of IMyCollection.
Let’s see how we might do this and be typesafe. The problem is that Items is writable via the interface.
Perfectly typesafe. This would be a legal C# 4 program.
If the design details of covariance and contravariance in C# 4 interests you, you might consider reading my dozen articles on the subject. You can find them here:
http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/
Note that these are listed in most-to-least-recent order; start from the bottom.
If in particular you are interested in the rules for determining when an interface’s annotations are valid, see this article (which I just discovered and fixed some errors in, so I’m glad we had this conversation.)
http://blogs.msdn.com/b/ericlippert/archive/2009/12/03/exact-rules-for-variance-validity.aspx