What is the generic version of a Hashtable?

The generic version of a Hashtable is the Dictionary<TKey,TValue> class (link). Here is some sample code translated from using a Hashtable into the most direct equivalent of Dictionary (argument checking removed for sake of brevity)

public HashTable Create(int[] keys, string[] values) { 
  HashTable table = new HashTable();
  for ( int i = 0; i < keys.Length; i++ ) {
    table[keys[i]] = values[i];
  }
  return table;
}

public Dictionary<object,object> Create(int[] keys, string[] values) {
  Dictionary<object,object> map = Dictionary<object,object>();
  for ( int i = 0; i < keys.Length; i++) {
    map[keys[i]] = values[i];
  }
  return map;
}

That's a fairly direct translation. But the problem is that this does not actually take advantage of the type safe features of generics. The second function could be written as follows and be much more type safe and inccur no boxing overhead

public Dictionary<int,string> Create(int[] keys, string[] values) {
  Dictionary<int,string> map = Dictionary<int,string>();
  for ( int i = 0; i < keys.Length; i++) {
    map[keys[i]] = values[i];
  }
  return map;
}

Even better. Here's a completely generic version

public Dictionary<TKey,TValue> Create<TKey,TValue>(TKey[] keys, TValue[] values) {
  Dictionary<TKey,TValue> map = Dictionary<TKey,TValue>();
  for ( int i = 0; i < keys.Length; i++) {
    map[keys[i]] = values[i];
  }
  return map;
}

And one that is even further flexible (thanks Joel for pointing out I missed this)

public Dictionary<TKey,TValue> Create<TKey,TValue>(
    IEnumerable<TKey> keys, 
    IEnumerable<TValue> values) {

  Dictionary<TKey,TValue> map = Dictionary<TKey,TValue>();
  using ( IEnumerater<TKey> keyEnum = keys.GetEnumerator() ) 
  using ( IEnumerator<TValue> valueEnum = values.GetEnumerator()) {
    while (keyEnum.MoveNext() && valueEnum.MoveNext() ) { 
      map[keyEnum.Current] = valueEnum.Current;
    }
  }
  return map;
}

The generic version of Hashtable class is System.Collections.Generic.Dictionary class.

Sample code:

Dictionary<int, string> numbers = new Dictionary<int, string>( );
   numbers.Add(1, "one");
   numbers.Add(2, "two");
   // Display all key/value pairs in the Dictionary.
   foreach (KeyValuePair<int, string> kvp in numbers)
   {
      Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value);
   }

Dictionary<TKey, TValue>

Note that Dictionary is not a 100% drop in replacement for HashTable.

There is a slight difference in the way they handle NULLs. The dictionary will throw an exception if you try to reference a key that doesn't exist. The HashTable will just return null. The reason is that the value might be a value type, which cannot be null. In a Hashtable the value was always Object, so returning null was at least possible.

Tags:

C#

.Net

Generics