10

Follow up question to a previous question, this has been identified as a co-variance issue. Taking this one step further, if I modify IFactory as follows:

class Program
{
    static void Main(string[] args)
    {
        IFactory<IProduct> factory = new Factory();
    }
}

class Factory : IFactory<Product>
{
}

class Product : IProduct
{
}

interface IFactory<out T> where T : IProduct
{
    List<T> MakeStuff();
}

interface IProduct
{
}

I get:

Invalid variance: The type parameter T must be invariantly valid on Sandbox.IFactory.MakeStuff(). T is covariant.

Why is this not invariantly valid? How can/should this be resolved?

Community
  • 1
  • 1
Firoso
  • 6,647
  • 10
  • 45
  • 91

3 Answers3

12

The other answers are correct but it is instructive to reason out why the compiler flags this as unsafe. Suppose we allowed it; what could go wrong?

class Sprocket: Product {}
class Gadget : Product {}
class GadgetFactory : IFactory<Gadget> 
{ 
    public List<Gadget> MakeStuff() 
    { 
        return new List<Gadget>() { new Gadget(); } 
    }
}
... later ...
IFactory<Gadget> gf = new GadgetFactory();
IFactory<Product> pf = gf; // Covariant!
List<Product> pl = pf.MakeStuff(); // Actually a list of gadgets
pl.Add(new Sprocket());

and hey, we just added a sprocket to a list that can only contain gadgets.

There is only one place where the compiler can detect the problem, and that's in the declaration of the interface.

Sorry about the somewhat excessively jargonish error message. I couldn't come up with anything better.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • Thank you for the feedback, I appreciate having more background, it seems I don't understand co and contravariance as well as I had thought. Always nice to have more background, now release part 4 of your immutability series :-P – Firoso Jun 20 '11 at 16:11
8

@Craig's answer is correct. To resolve, change it to:

IEnumerable<T> MakeStuff()

EDIT: As to the why, look at the definition of IEnumerable<T> Interface:

public interface IEnumerable<out T> : IEnumerable

Note that the IList<T> Interface does not have the out keyword. Variance is supported for generic type parameters in interfaces and delegates, not classes, so it doesn't apply to List<T>.

Community
  • 1
  • 1
TrueWill
  • 25,132
  • 10
  • 101
  • 150
  • 2
    Note that after this answer was written, a new version of the .NET Framework has been released in which `List` implements a new interface `IReadOnlyList`. As indicated that interface is covariant just like `IEnumerable`. – Jeppe Stig Nielsen Sep 28 '13 at 19:14
7

Because you can add and remove objects from a List<T>, T must always be invariant, even if the list is a function result. Having executed var l = MakeStuff() you can then put stuff in the list or take it out, so T must be invariant.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273