0
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

enashnash
  • 1,578
  • 1
  • 15
  • 36
  • 1
    where are the [out](http://msdn.microsoft.com/en-us/library/dd469487.aspx) and [in](http://msdn.microsoft.com/en-us/library/dd469484.aspx) generic modifiers before the generic parameter usually associated with covariance and contravariance? – bottlenecked Apr 07 '11 at 11:39
  • Variance is only allowed in interfaces and and in delegates. And it is not the default. It's something you need to make explicit with `in` and `out`. – R. Martinho Fernandes Apr 07 '11 at 11:41
  • Well that was the point really, I tried a few different ways and I couldn't get anything to work! – enashnash Apr 07 '11 at 11:42

3 Answers3

15

To use generic variance in C# you have to meet all the following conditions:

  1. Use C# 4
  2. The type that varies must be a generic interface or generic delegate
  3. The type parameter must be marked "in" (contravariant) or "out" (covariant)
  4. The type parameter annotations must yield a type which is provably typesafe in all its possible operations
  5. The "source" type argument and the "destination" type argument must have an identity or reference conversion between them.

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:

// Suppose this declaration were legal:
interface IMyCollection<out T> 
{
  List<T> Items { get; set; } 
}

class Animal {}
class AnimalCollection : IMyCollection<Animal> 
{ 
  public List<Animal> { get; set; }
}

class Giraffe : Animal {}
class GiraffeCollection : IMyCollection<Giraffe> 
{
  public List<Giraffe> { get; set; } 
}

static class X 
{
  public IMyCollection<Animal> GetThing() 
  {
    // IMyCollection is covariant in T, so this is legal.
    return new GiraffeCollection(); 
  }
}

class Tiger : Animal {}

...

IMyCollection<Animal> animals = X.GetThing(); 
// GetThing() actually returns a GiraffeCollection
animals.Items = new List<Animal>() { new Tiger(); }

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.

interface IMyCollection<out T> 
{
  IEnumerable<T> Items { get; }
}

class Animal {}
class AnimalCollection : IMyCollection<Animal> 
{ 
  public IEnumerable<Animal> { get { yield return new Tiger(); } }
}

class Giraffe : Animal {}
class GiraffeCollection : IMyCollection<Giraffe> 
{
  public IEnumerable<Giraffe> { get { yield return new Giraffe(); } } 
}

static class X 
{
  public IMyCollection<Animal> GetThing() 
  {
    return new GiraffeCollection();
  }
}

class Tiger : Animal {}

...

MyCollection<Animal> animals = X.GetThing(); 
// GetThing() actually returns a GiraffeCollection
foreach(Animal animal in animals.Items) { ... } 
// Items yields a giraffe, which is an animal

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

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
3

There is no relation between E and C. So your return type must be A<B> which may be considered as a common parent to those types. Also A needs to be an interface where the generic argument is defined with out for this to work:

interface A<out T> { }

class B { }
class C : A<B> { }

class D : B { }
class E : A<D> { }

static class X
{
    public static A<B> GetThing(bool f)
    {
        if (f)
        {
            return new E();
        }
        return new C();
    }
}

Couldn't make it work with the ternary operator (?:). The compiler simply doesn't like it.


UPDATE:

After @Eric Lippert's excellent remark in the comments section you could use the ternary operator by casting to A<B>:

public static A<B> GetThing(bool f)
{
    return f ? (A<B>)new E() : new C();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Actually I did have `A` as the return type, that was a typo, so I'll update the question. Incidentally, my A abstract class contains a property `virtual List { get; set; }` which causes a problem too... – enashnash Apr 07 '11 at 11:53
  • Sorry, that should have been `List Items { get; set; }` – enashnash Apr 07 '11 at 12:06
  • 1
    If you cast one or both sides of the : to A then the conditional operator should work. The problem is that the conditional operator tries to find a type that is the type of the expression **and that type must be the type of at least one of the consequence or alternative**. In C# we never "magic up" a type that doesn't appear in the expression. We don't say "foo ? giraffe : cat", oh, neither Giraffe nor Cat are convertible to each other, let's pick Mammal. Mammal isn't an option because it doesn't appear. – Eric Lippert Apr 07 '11 at 14:05
  • @Eric Lippert, thanks for this valuable precision. I've updated my answer to take it into account. @enashnash, because `T` is covariant in the generic `A` interface definition you can only have the generic argument as input argument. You cannot have it appear as a method result so this cannot work in your case because you have a property returning `List`. – Darin Dimitrov Apr 07 '11 at 14:10
0

This cannot work because C and E have no common parent. To something like this you need to create a common parent type, be it a class or an interface.

Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53