KeyValuePair vs. DictionaryEntry [Krzysztof Cwalina]

KeyValuePair vs. DictionaryEntry [Krzysztof Cwalina]

  • Comments 2

We discussed a problem with implementation of IEnumerable on Dictionary<K,V>. What type should IEnumerable.GetEnumerator().Current return? KeyValuePair<K,V> or DictionaryEntry? Same for ICollection.CopyTo. Instances of what type should be copied to the array?

We decided the following:

  1. IEnumerable and ICollection interface implementations will use KeyValuePair<K,V> as the item type.
  2. IDictionary specific members (GetEnumerator returning IDictionaryEnumerator) will use DictionaryEntry as the item type.

The reason is that we are in a process of making a change where IEnumerator<T> would extend IEnumerator. It would be very strange if walking the hierarchy from Dictionary<K,V>->IEnumerable<T>->IEnumerable we suddenly changed the type of the item returned from enumerators.

  • Just curious - why was Dictionary templated as Dictionary<K, V> but DictionaryEntry was replaced by KeyValuePair<K, V>? Wouldn't it make more sense to use DictionaryEntry<K, V>?
  • The only comment I have on this is that if you're going to return one type, make sure that it's easily converted to the other and visa versa. There are a couple of places in the .net framework where you have to work damn hard to get it from one type or another (I can't remember the case I'm thinking of of the top of my head) and it really sucks for readability (and figuring it out in the first place!)
Page 1 of 1 (2 items)