Dominic Jonas
Dominic Jonas

Reputation: 5005

use a dictionary with an interface as value for method parameter

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.

Upvotes: 0

Views: 538

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

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 { /* ... */ }

Upvotes: 4

Related Questions