I noticed that key-value pairs can only be added to Dictionaries if the variable is declared as an IDictionary<TKey, TValue>. Which caused me to dig further down the rabbit hole, leading me to discover that there seems to be an odd discrepancy:
Microsoft Docs explicitly confirm that
IDictionary<TKey, TValue>implementsIEnumerable<T>
Microsoft Docs Screenshot - IDictionary Implements implementsIEnumerable<T>Using the Visual Studio's Reflector Tool on mscorlib,
IDictionary<TKey, TValue>seems to not implementIEnumerable<T>Reflector Tool Screenshot - mscorlib, IDictionary seems to not implement
IEnumerable<T>
Any explanation will be helpful to sate this curious mind!
It does show that it implements
IEnumerable<T>:For a
Dictionary<TKey, TValue>, the collection element's type isKeyValuePair<TKey, TValue>. In essence, a dictionary is an enumerable list of key/value pairs (of the chosen key/value types), so it implements theIEnumerable<KeyValuePair<TKey, TValue>>interface.The MSDN docs show both the generic
IEnumerable<T>interface, and the more concreteIEnumerable<KeyValuePair<TKey, TValue>>, but they are referring to the same implementation. TheTinIEnumerable<T>is effectivelyKeyValuePair<TKey, TValue>.This isn't a case of the real code missing a documented feature. It's a case of MSDN documenting the same interface implementation twice, by referring to both the generic
IEnumerable<T>and the more concrete type where it shows whatTis being defined as (i.e.KeyValuePair<TKey, TValue>).If you think about it, it doesn't make sense to have
Dictionary<TKey, TValue> : IEnumerable<T>sinceTwas never defined to begin with. Any generic type that appears after the:must either be hardcoded or defined as a generic type before the:, andTis neither hardcoded nor defined, so it's not valid syntax.You can easily confirm this behavior:
Knowing this, let's look back at the dictionary:
But this is valid:
KeyValuePair<TKey, TValue>consists of 3 distinct types, and all of them conform to the rules:KeyValuePairis hardcoded (it's a known type)TKeyis a defined generic type fromDictionary<TKey, TValue>TValueis a defined generic type fromDictionary<TKey, TValue>And therefore this class definition is syntactically valid.