Skip to content

HashSet vs Dictionary vs Hashtable

↑

A HashSet<T> holds unique values, ideal for membership tests and union/intersection operations. A Dictionary<TKey,TValue> maps unique keys to values. Hashtable is the older non-generic collection storing object keys and values and usually should not be chosen for new code. The term hash table also describes the underlying data-structure family rather than specifically .NET’s Hashtable class.

Neither HashSet<T> nor Dictionary<TKey,TValue> promises a particular enumeration order. Do not depend on their internal buckets, or treat their bucket count as a public implementation contract.

C# | Example.cs
var onlineIds = new HashSet<int>();
Console.WriteLine(onlineIds.Add(42)); // True
Console.WriteLine(onlineIds.Add(42)); // False, already exists
Console.WriteLine(onlineIds.Contains(42)); // True
var players = new Dictionary<int, string>();
players[42] = "Ada";
if (players.TryGetValue(42, out string? name))
Console.WriteLine(name);

When: Choose HashSet<int> for whitelists, deduplication and visited nodes; Dictionary<int,Player> for entity lookup; List<T> when order and duplicates matter. Pitfall: Mutating an object in ways that change its hash/equality while stored as a key can break lookups.

Interactive hash table · HashSet and Dictionary