137

What is the difference between KeyValuePair which is the generic version and DictionaryEntry?

Why KeyValuePair is used instead of DictionaryEntry in generic Dictionary class?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Jaywith.7
  • 1,819
  • 4
  • 15
  • 13

3 Answers3

125

KeyValuePair<TKey,TValue> is used in place of DictionaryEntry because it is generified. The advantage of using a KeyValuePair<TKey,TValue> is that we can give the compiler more information about what is in our dictionary. To expand on Chris' example (in which we have two dictionaries containing <string, int> pairs).

Dictionary<string, int> dict = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in dict) {
  int i = item.Value;
}

Hashtable hashtable = new Hashtable();
foreach (DictionaryEntry item in hashtable) {
  // Cast required because compiler doesn't know it's a <string, int> pair.
  int i = (int) item.Value;
}
cdmckay
  • 31,832
  • 25
  • 83
  • 114
56

KeyValuePair < T,T > is for iterating through Dictionary < T,T >. This is the .Net 2 (and onwards) way of doing things.

DictionaryEntry is for iterating through HashTables. This is the .Net 1 way of doing things.

Here's an example:

Dictionary<string, int> MyDictionary = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in MyDictionary)
{
  // ...
}

Hashtable MyHashtable = new Hashtable();
foreach (DictionaryEntry item in MyHashtable)
{
  // ...
}
Chris
  • 39,719
  • 45
  • 189
  • 235
  • 4
    KeyValuePair is Generics, the other is pre-generics. Use of the former is recommended going fwd. – Gishu May 25 '09 at 06:00
  • 1
    I think he understands that one is for generics, and one is for non-generics. I think his question is why do we need both? – cdmckay May 25 '09 at 19:49
  • 4
    If that's what he's asking, well, we don't really need both - its just that generics weren't available until .net 2, and they left the non-generics stuff in for backwards compatability. Some people may still like to use the non-generic stuff, but its not highly recommended. – Chris May 25 '09 at 23:40
  • This answer made more sense to me. – Merin Nakarmi Dec 27 '17 at 01:15
14

This is how the issue is explained. see the following link:

https://www.manojphadnis.net/need-to-know-general-topics/listkeyvaluepair-vs-dictionary

List< KeyValuePair >

  1. Lighter

  2. Insertion is faster in List

  3. Searching is slower than Dictionary

  4. This can be serialized to XMLSerializer

  5. Changing the key,value is not possible. Keyvaluepair can be assigned value only during creation. If you want to change then remove and add new item in same place.

Dictionary<T Key, T Value>

  1. Heavy

  2. Insertion is slower. Has to compute Hash

  3. Searching is faster because of Hash.

  4. Can't be serialized. Custom code is required.

  5. You can change and update dictionary.

HamzeLue
  • 311
  • 3
  • 8