0

Why isn't it possible to pass

Dictionary<string, PinkLady>()

into my Supply(Dictionary<string, IApple> apples) method?

public interface IApple { }

public class PinkLady : IApple { }

public void Supply(Dictionary<string, IApple> apples) { }

public void TestMethod()
{
    //Working
    Supply(new Dictionary<string, IApple>());

    //Not working
    Supply(new Dictionary<string, PinkLady>());
}

I always get an error:

converting from Dictionary into Dictionary not possible. PinkLady does not match expected type IApple.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Dominic Jonas
  • 4,717
  • 1
  • 34
  • 77
  • 1
    Please read this https://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example – Andrey Belykh Oct 19 '17 at 15:36
  • 1
    You're asking it to guarantee that an instance of `Dictionary` can safely be treated as `Dictionary` in all cases. But `Dictionary` guarantees that you can call `Add(myCortland)` on it, and `Dictionary` guarantees that you can't. – 15ee8f99-57ff-4f92-890c-b56153 Oct 19 '17 at 15:40

1 Answers1

4

Because the types Dictionary<string, IApple> and Dictionary<string, PinkyLady> are not the same types. PinkyLady might derive from IApple but this is in the context of Dictionary being generic. They compile into two different types.

What you can do to solve it is make Support a generic method with a constraint:

public void Supply<T>(Dictionary<string, T> apples) where T : IApple { /* ... */ }
Gilad Green
  • 36,708
  • 7
  • 61
  • 95