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.)
In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations.
At compile time, the compiler chooses which overload to use based on the types and number of arguments passed in by the caller. If you call print(42.0) , then the void print(double d) function is invoked. If you call print("hello world") , then the void print(std::string) overload is invoked.
Function Overloading in C++When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading can be considered as an example of a polymorphism feature in C++.
In Function overloading, sometimes a situation can occur when the compiler is unable to choose between two correctly overloaded functions. This situation is said to be ambiguous. Ambiguous statements are error-generating statements and the programs containing ambiguity will not compile.
To provide a solution to the problem (see comment too):
Console.WriteLine(
((ICollection<KeyValuePair<object, object>) d2).
Remove(new KeyValuePair<object, object>("1", 2)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With