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