See this question about converting from List<Dog>
to List<Animal>
for why you can't do this directly. Here's the dictionary-specific explanation, imagine that you can do:
// here, myDict is of type Dictionary<Foo, Bar>, as we are outside SomeMethod
// suppose myDict is empty initially
SomeMethod(myDict);
And then SomeMethod
could do:
// here, myDict is of type Dictionary<IFoo, IBar>, as we are inside SomeMethod
myDict.Add[new AnotherClass1(), new AnotherClass2());
where
class AnotherClass1: IFoo {}
class AnotherClass2: IBar {}
After SomeMethod
returns, you do:
// here, myDict is Dictionary<Foo, Bar> again, we are outside SomeMethod
Bar firstValue = myDict.Values.First();
Wait... firstValue
should be of type AnotherClass2
!
See the problem?
Rather than creating a new Dictionary<IFoo, IBar>
with the same values,
Dictionary<IFoo, IBar> newDict = myDict.ToDictionary(x => x.Key, y => y.Value);
which could take some time (and the modifications to the dictionary that SomeMethod
does won't reflect not the original dictionary), you can also make SomeMethod
generic:
public void SomeMethod<TFoo, TBar>(Dictionary< TFoo, TBar> myDict)
where TFoo: IFoo
where TBar: IBar
{
// the method can be implemented the same way as before
}