Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyValuePair VS DictionaryEntry

Tags:

c#

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

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