C# `Hashtable` vs. `Dictionary`: Comparing Key-Value Data Structures

Compare and contrast C#'s `Hashtable` and `Dictionary` classes for storing and retrieving key-value pairs. This tutorial examines their differences (generic vs. non-generic, type safety, performance), highlighting when to use `Hashtable` and when `Dictionary` is the more suitable choice for efficient and type-safe data management.



`Hashtable` vs. `Dictionary` in C#

Both `Hashtable` and `Dictionary` in C# are used to store key-value pairs, but they have key differences in terms of type safety, performance, and features. Understanding these differences helps you choose the most appropriate collection for your needs.

`Hashtable`

The `Hashtable` class (part of `System.Collections`) is a non-generic collection that stores key-value pairs. It uses a hash function to map keys to their corresponding values, enabling fast lookups. Keys must be unique, but values can be duplicated. Keys cannot be null.

Key Characteristics of `Hashtable`

  • Key-Value Pairs: Stores data as key-value pairs.
  • Hashing: Uses hashing for efficient lookups.
  • Dynamic Sizing: Grows automatically as needed.
  • No Guaranteed Order: Element order is not preserved.
  • Not Type-Safe: Keys and values can be of any type (requires boxing/unboxing).

Example: Using `Hashtable`


Hashtable myHashtable = new Hashtable();
myHashtable.Add("apple", 1);
myHashtable.Add("banana", 2);
// ... (code to access values using keys, modify values, remove key-value pairs, and iterate) ...

`Dictionary`

The `Dictionary` class (part of `System.Collections.Generic`) is a generic collection that also stores key-value pairs. It offers type safety and generally better performance than `Hashtable`.

Key Characteristics of `Dictionary`

  • Key-Value Pairs: Stores data as key-value pairs.
  • Hashing: Uses hashing for efficient lookups.
  • Dynamic Sizing: Grows automatically as needed.
  • No Guaranteed Order: Element order is not preserved.
  • Type-Safe: Keys and values are strongly typed; you specify the types when creating the dictionary.
  • LINQ Support: You can use LINQ to query and manipulate the dictionary's contents.

Example: Using `Dictionary`


Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("apple", 1);
myDictionary.Add("banana", 2);
// ... (code to access values using keys, modify values, remove key-value pairs, and iterate) ...

Key Differences: `Hashtable` vs. `Dictionary`

Feature `Hashtable` `Dictionary`
Type Safety Not type-safe Type-safe
Performance Can be slower due to boxing/unboxing Generally faster
Key Types Any type (except null) Specific type (specified when creating the dictionary)
LINQ Support No direct LINQ support Direct LINQ support