KeyValuePair VS DictionaryEntry

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

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


Solution 1:

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;
}

Solution 2:

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)
{
  // ...
}

Solution 3:

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.