C #: How can the dictionary <K, V> implement ICollection <KeyValuePair <K, V >> without adding (KeyValuePair <K, V>)?
Looking at System.Collections.Generic.Dictionary<TKey, TValue> , it explicitly implements ICollection<KeyValuePair<TKey, TValue>> , but does not have the required function " void Add(KeyValuePair<TKey, TValue> item) ".
This can also be seen when trying to initialize the Dictionary as follows:
private const Dictionary<string, int> PropertyIDs = new Dictionary<string, int>() { new KeyValuePair<string,int>("muh", 2) }; which fails with
No overload for the 'Add' method takes '1' arguments
Why is this so?
The expected API should add the Add(key,value) method (or the this[key] index Add(key,value) through two arguments; as such, it uses an explicit interface implementation to provide the Add(KeyValuePair<,>) method Add(KeyValuePair<,>) .
If you use the IDictionary<string, int> interface instead, you will have access to the missing method (since you cannot hide anything on the interface).
Also, with the collection initializer, note that you can use alternative syntax:
Dictionary<string, int> PropertyIDs = new Dictionary<string, int> { {"abc",1}, {"def",2}, {"ghi",3} } which uses the Add(key,value) method.
Some interface methods are implemented explicitly . If you use a reflector, you can see explicitly implemented methods that:
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair); bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair); void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index); bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair); IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator(); void ICollection.CopyTo(Array array, int index); void IDictionary.Add(object key, object value); bool IDictionary.Contains(object key); IDictionaryEnumerator IDictionary.GetEnumerator(); void IDictionary.Remove(object key); IEnumerator IEnumerable.GetEnumerator(); It does not implement ICollection<KeyValuePair<K,V>> directly. It implements IDictionary<K,V> .
IDictionary<K,V> comes from ICollection<KeyValuePair<K,V>> .