Hashtable vs Dictionary in C#

By FoxLearn 1/7/2025 3:30:14 AM   62
The Microsoft .NET Framework offers strong support for working with collections, which are used to store and retrieve data.

Collections allow dynamic memory allocation to store elements, enabling you to access them using keys or indexes as needed.

Hashtable

The types in the System.Collections namespace store data as objects of type Object.

A Hashtable is a data structure that stores key-value pairs, where both the key and the value are of the Object type. You can retrieve a value by searching for its corresponding key, but note that the key cannot be null, although the value can be.

For example, how to store and retrieve key-value pairs in a Hashtable:

static void Main()
{
    Hashtable hashTable = new Hashtable();

    hashTable.Add(1, "Alice");
    hashTable.Add(2, "Bob");
    hashTable.Add(3, "Charlie");

    Console.WriteLine("The key / value pairs are:");

    foreach (int key in hashTable.Keys)
    {
        Console.WriteLine("Key: " + key + " Value: " + hashTable[key].ToString());
    }

    Console.Read();
}

You can also use the GetEnumerator() method of the Hashtable class to enumerate through the collection and retrieve the key-value pairs.

IDictionaryEnumerator enumerator = hashTable.GetEnumerator();

while (enumerator.MoveNext())
{
    Console.WriteLine("Key: " + enumerator.Key.ToString() + " Value: " + enumerator.Value.ToString());
}

Another way to iterate through the Hashtable is by using the DictionaryEntry class, which provides both the key and the value in each iteration:

Hashtable hashTable = new Hashtable();

hashTable.Add(1, "Alice");
hashTable.Add(2, "Bob");
hashTable.Add(3, "Charlie");

foreach (DictionaryEntry dictionaryEntry in hashTable)
{
    Console.WriteLine("Key: " + dictionaryEntry.Key.ToString() + " Value: " + dictionaryEntry.Value.ToString());
}

Searching for an item in a Hashtable is faster than in other non-generic collections. This is because a Hashtable organizes records into buckets, each of which can contain multiple entries. The key for each record is hashed, and the hash code determines which bucket the record belongs to. When you perform a lookup, the algorithm uses the hash code to access only the relevant bucket, greatly reducing the number of comparisons needed to find the desired element.

Dictionary

The System.Collections.Generic namespace includes several essential classes, such as List, Queue, HashSet, LinkedList, Stack, LinkedListNode, and Dictionary. The Dictionary class in C# is a generic data structure designed to hold key-value pairs, allowing you to store data of any type in a strongly-typed collection.

It’s important to understand that while the ICollection interface extends IEnumerable, both the IDictionary and IList interfaces extend ICollection. The Dictionary class, which resides in the System.Collections.Generic namespace, essentially stores a collection of key-value pairs. You can use the Add method to insert objects into a Dictionary instance. Compared to a Hashtable, a Dictionary is more efficient because it eliminates the overhead of boxing and unboxing, making it a faster choice for type-safe collections.

For example, how to store and retrieve key-value pairs in a Dictionary instance:

Dictionary<int, string> dictionary = new Dictionary<int, string>();

dictionary.Add(1, "Alice");
dictionary.Add(2, "Bob");
dictionary.Add(3, "Charlie");

foreach (KeyValuePair<int, string> kvp in dictionary)
{
    Console.WriteLine(kvp.Key.ToString() + " - " + kvp.Value.ToString());
}

The main difference between a Hashtable and a Dictionary is that a Hashtable is untyped and requires boxing and unboxing, while a Dictionary is strongly typed and avoids this overhead. Additionally, when retrieving values, a Hashtable returns null for non-existent keys, while a Dictionary throws an exception. Neither guarantees the order of items. A Dictionary is typically a better choice due to its type safety and efficiency, making it an improved version of a Hashtable.