
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Replacing the Hashtable with Its Generic Counterpart
|
271
Solution
Replace all occurrences of the System.Collections.Hashtable class with the faster
generic
System.Collections.Generic.Dictionary class.
Here is a simple example of using a
System.Collections.Hashtable object:
public static void UseNonGenericHashtable( )
{
// Create and populate a Hashtable.
Hashtable numbers = new Hashtable( );
numbers.Add(1, "one"); // Causes a boxing operation to occur for the key
numbers.Add(2, "two"); // Causes a boxing operation to occur for the key
// Display all key/value pairs in the Hashtable.
// Causes an unboxing operation to occur on each iteration for the key
foreach (DictionaryEntry de in numbers)
{
Console.WriteLine("Key: " + de.Key + "\tValue: " + de.Value);
}
numbers.Clear( );
}
Here is that same code using a System.Collections.Generic.Dictionary<T,U> object:
public static void UseGenericDictionary( )
{
// Create and populate a Dictionary.
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);
}
numbers.Clear( );
}
Discussion
For simple implementations of the Hashtable ...