enashnash
enashnash

Reputation: 1578

Can't get co/contra-variance to work in C#

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

Upvotes: 0

Views: 332

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 660038

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

Upvotes: 15

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

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();
}

Upvotes: 3

Florian Greinacher
Florian Greinacher

Reputation: 14784

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.

Upvotes: 0

Related Questions