SoFunction
Updated on 2025-04-13

Comparison and selection of Hashtable and Dictionary in C#

In C#,HashtableandDictionaryThey are all data structures used to store key-value pairs, but there are some key differences between them.

Here are detailed descriptions of these differences, with examples:

1. Type safety

  • Hashtable: Non-generic collections, keys and values ​​areobjecttype. This means that boxing and unboxing operations are required when storing or retrieving data, which can lead to performance losses and additional type conversions.
  • Dictionary: Generic collection, which can specify the types of keys and values. This provides better type safety, because types are checked at compile time, avoiding runtime type conversion errors.

Example:

// Hashtable exampleHashtable hashtable = new Hashtable();
(1, "one"); // The key is type int, the value is type string("key", 42); // The key is of type string and the value is of type int// Type conversion is required to retrieve the valuestring value1 = (string)hashtable[1];
int value2 = (int)hashtable["key"];

// Dictionary exampleDictionary<int, string> dictionary = new Dictionary<int, string>();
(1, "one"); // The key and value types are explicitly specifiedstring valFromDict = dictionary[1]; // No type conversion required

2. Storage order

  • Hashtable: Unordered collection. The order of storage of elements is not in the order of insertion.
  • Dictionary: In .NET Framework 3.5 and later,DictionaryKey-value pairs are stored in the order of insertion. This means traversalDictionaryWhen the elements are returned in the order they are added to the collection.

Example:

// Hashtable disordered exampleHashtable unorderedHashtable = new Hashtable();
("a", 1);
("b", 2);
("c", 3);
// The traversal order may not be "a", "b", "c"foreach (DictionaryEntry entry in unorderedHashtable)
{
    ($"{}: {}");
}

// Dictionary Ordering ExampleDictionary<string, int> orderedDictionary = new Dictionary<string, int>();
("a", 1);
("b", 2);
("c", 3);
// The traversal order will be "a", "b", "c"foreach (KeyValuePair<string, int> kvp in orderedDictionary)
{
    ($"{}: {}");
}

3. Allowed types of keys and values

  • Hashtable: Allow keys and values ​​to benull
  • Dictionary: The key or value is not allowednull. If you try to addnullkey or value, will be thrownArgumentNullException

Example:

// Hashtable allows null key and value exampleHashtable hashtableWithNulls = new Hashtable();
(null, "nullValue");
("nullKey", null);

// Dictionary does not allow null key and value examplestry
{
    Dictionary<string, string> dictionaryWithNoNulls = new Dictionary<string, string>();
    (null, "this will throw an exception"); // ArgumentNullException will be thrown}
catch (ArgumentNullException ex)
{
    (); // Output error message}

4. Thread safety

  • Hashtable: is thread-safe (only for single-thread write and multi-thread read scenarios). But performance may be affected because it requires maintenance of thread synchronization. Can be called bySynchronized()Method to obtain a thread-safeHashtableWrapper.
  • Dictionary: Non-thread-safe. When used in multithreaded environments, external synchronization mechanisms are required (e.g.lockstatement) to protect theDictionaryvisit.

5. Performance

  • Hashtable: Because it is non-generic and may involve packing and unboxing operations, the performance may be low.
  • Dictionary: Since it is generic, boxing and unboxing operations are avoided and usually have better performance. But in certain specific cases (such as when the key is of string type),Hashtableperformance may be better thanDictionary

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.