How does this overload resolution make any sense?

c#, overloading

Solution

To provide a solution to the problem (see comment too):

Console.WriteLine( 
   ((ICollection<KeyValuePair<object, object>) d2).
      Remove(new KeyValuePair<object, object>("1", 2)));

Problem

I just had a unit test fail for a strange reason involving `IDictionary<object, object>`. `IDictionary<K,V>` has two `Remove` methods. One takes a `K`, the other takes a `KeyValuePair<K,V>`. Consider these two dictionaries that are very similar to each other, but don't quite act the same: ``` IDictionary<string, object> d1 = new Dictionary<string, object>(); IDictionary<object, object> d2 = new Dictionary<object, object>(); d1.Add("1", 2); d2.Add("1", 2); Console.WriteLine(d1.Remove(new KeyValuePair<string, object>("1", 2))); Console.WriteLine(d2.Remove(new KeyValuePair<object, object>("1", 2))); ``` The output is `True`, then `False`. Since `KeyValuePair<object,object>` is the exact type expected by `d2.Remove(KeyValuePair<object,object>)`, why does the compiler call `d2.Remove(object)` instead? (Post-mortem note: In the scenario that prompted my question, I wasn't using `IDictionary<object,object>` directly but rather through a generic parameter: ``` public class DictionaryTests<DictT> where DictT : IDictionary<object,object>, new() ``` since the problem is that `IDictionary` took priority over `ICollection` I decided to "even things out" by including `ICollection` in the list of constraints: ``` public class DictionaryTests<DictT> where DictT : ICollection<KeyValuePair<object, object>>, IDictionary<object,object>, new() ``` but this didn't change the compiler's mind... I wonder why not.)

Original source

Related problems