Hashtable

Intro

Hashtable is the non-generic hash table from System.Collections. It is mostly legacy in modern .NET and is usually replaced by Dictionary<TKey, TValue>.

Deeper Explanation

Hashtable stores keys and values as object, so value types are boxed/unboxed.
It still uses hash buckets and collision resolution similar to modern hash-based collections.

Internally, Hashtable uses separate chaining: when two keys hash to the same bucket, they form a linked list at that slot. Lookup traverses the chain until the matching key is found, making worst-case performance O(n) when all keys collide. Dictionary<TKey, TValue> uses open addressing with prime-based probing, which is more cache-friendly and avoids per-collision heap allocations. This is the primary performance reason to prefer Dictionary in new code.

Structure

graph TD
    K1[object key one hash] --> B0[bucket zero]
    K2[object key two hash] --> B1[bucket one]
    B0 --> E1[object key one value ann]
    B1 --> E2[object key two value bob]

Example

var table = new Hashtable
{
    ["user:1"] = "Ann"
};

var value = table["user:1"]; // object

Pitfalls

Tradeoffs

Questions

Hash-Based Collections Comparison

Type Key type Type-safe When to use
Hashtable object No Legacy interop only
Dictionary<TKey,TValue> Generic Yes Default key-value map in modern .NET
ConcurrentDictionary<TKey,TValue> Generic Yes Concurrent read/write

Decision rule: do not use Hashtable in new code. Migrate to Dictionary<TKey,TValue> for type safety and better performance.


Whats next