Matias Cicero Matias Cicero - 2 months ago 11
C# Question

How come Dictionary does not implement Add(KeyValuePair)

IDictionary<TKey, TValue>
extends from interface
ICollection<KeyValuePair<TKey, TValue>>
, so it has an
Add(KeyValuePair<TKey, TValue> item)
method:

IDictionary<string, object> dic = new Dictionary<string, object>();
dic.Add(new KeyValuePair<string, object>("number", 42)); // Compiles fine


However, although
Dictionary<TKey, Tvalue>
implements
IDictionary<TKey, TValue>
, it does not have this method overload:

Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add(new KeyValuePair<string, object>("number", 42)); // Does not compile


How can this be?

Answer

As you can see in the documentation and in the reference source, Dictionary<TKey, TValue> implements this part of the ICollection<KeyValuePair<TKey, TValue>> interface explicitly.

void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) 
{
    Add(keyValuePair.Key, keyValuePair.Value);
}

As you have discovered, you can only call it by casting to IDictionary<TKey, TValue> or ICollection<KeyValuePair<TKey, TValue>>.

You might want to see this related question on the difference between implicit and explicit interface implementation.