I wanted to write an extension-method that would work on dictionaries whose values were some sort of sequence. Unfortunately, the compiler can't seem to infer the generic arguments from my usage of the method; I need to specify them explicitly.
public static void SomeMethod<TKey, TUnderlyingValue, TValue> (this IDictionary<TKey, TValue> dict) where TValue : IEnumerable<TUnderlyingValue> { } static void Usage() { var dict = new Dictionary<int, string[]>(); var dict2 = new Dictionary<int, IEnumerable<string>>(); //These don't compile dict.SomeMethod(); SomeMethod(dict); // doesn't have anything to do with extension-methods dict2.SomeMethod(); // hoped this would be easier to infer but no joy //These work fine dict.SomeMethod<int, string, string[]>(); dict2.SomeMethod<int, string, IEnumerable<string>>(); } I realize that type inference isn't an exact science, but I was wondering if there's some fundamental 'rule' I'm missing here - I'm not familiar with the details of the spec.
- Is this a shortcoming of the inference process or is my expectation that the compiler should "figure it out" unreasonable in this case (ambiguity perhaps)?
- Can I change the method's signature in a way that would make it equally functional yet 'inferrable'?
IEnumerable<>is covariant in .net 4.