HashSet vs Dictionary vs Hashtable
↑How it works and why
Section titled “How it works and why”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# and C++ examples
Section titled “C# and C++ examples”var onlineIds = new HashSet<int>();Console.WriteLine(onlineIds.Add(42)); // TrueConsole.WriteLine(onlineIds.Add(42)); // False, already existsConsole.WriteLine(onlineIds.Contains(42)); // True
var players = new Dictionary<int, string>();players[42] = "Ada";if (players.TryGetValue(42, out string? name)) Console.WriteLine(name);#include <unordered_set>#include <unordered_map>#include <string>#include <iostream>
std::unordered_set<int> onlineIds;std::cout << onlineIds.insert(42).second << '\n'; // 1std::cout << onlineIds.insert(42).second << '\n'; // 0std::cout << onlineIds.contains(42) << '\n'; // 1 (C++20)
std::unordered_map<int, std::string> players;players[42] = "Ada";if (auto it = players.find(42); it != players.end()) std::cout << it->second << '\n';When and why to use it
Section titled “When and why to use it”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.
