C# Hashtable vs Dictionary: Key-Value Examples

A hash table stores key-value pairs and finds a value by its key in roughly constant time, no matter how many entries it holds. In current .NET, that type is Dictionary<TKey, TValue>. The older Hashtable class does the same job with object keys and values; it is covered at the end for people maintaining legacy code.

Dictionary basics

var capitals = new Dictionary<string, string>
{
    ["France"] = "Paris",
    ["Japan"] = "Tokyo"
};

capitals.Add("Turkey", "Ankara");   // throws if the key already exists
capitals["Italy"] = "Rome";          // adds, or overwrites an existing value

if (capitals.TryGetValue("Japan", out string? capital))
{
    Console.WriteLine(capital);                        // Tokyo
}

Console.WriteLine(capitals.ContainsKey("Spain"));      // False
Console.WriteLine(capitals.ContainsValue("Paris"));    // True

foreach (var (country, city) in capitals)
{
    Console.WriteLine($"{country} = {city}");
}

The foreach loop gets KeyValuePair<string, string> items, deconstructed here into two variables. You can also write foreach (var pair in capitals) and use pair.Key and pair.Value.

The traps

Reading a missing key throws. capitals["Spain"] throws KeyNotFoundException. When a key may be absent, use TryGetValue, which does the lookup once. Checking ContainsKey and then using the indexer works too, but it hashes the key twice.

Add throws on duplicates, the indexer does not. Add throws ArgumentException if the key exists. The indexer silently replaces the value. TryAdd (since .NET Core 2.0) adds only if the key is new and returns false otherwise. Pick the one that matches what a duplicate means in your code.

ContainsValue is slow. Keys are hashed; values are not. ContainsValue checks every entry, so it is O(n). If you look things up by value often, keep a second dictionary going the other way.

Order is not guaranteed. In practice a dictionary that has never had items removed enumerates in insertion order, but the documentation makes no promise. If you need sorted keys, use SortedDictionary<TKey, TValue>. If you need insertion order, .NET 9 added OrderedDictionary<TKey, TValue>.

String keys are case-sensitive. "france" and "France" are different keys. Pass a comparer when that is not what you want:

var settings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
settings["Theme"] = "dark";
Console.WriteLine(settings["THEME"]);   // dark

Mutable keys. If you use your own class as a key, it must override Equals and GetHashCode consistently, and the fields that feed the hash must not change while the object is in the dictionary. Records handle the first part for you.

Counting with a dictionary

A frequent use is counting occurrences:

string[] words = ["apple", "pear", "apple", "fig", "apple", "pear"];
var counts = new Dictionary<string, int>();

foreach (string word in words)
{
    counts[word] = counts.GetValueOrDefault(word) + 1;
}

Console.WriteLine(counts["apple"]);   // 3
Console.WriteLine(counts["pear"]);    // 2

GetValueOrDefault returns 0 for a missing int key, so the first occurrence becomes 1. For a one-off count, LINQ’s CountBy (.NET 9) or GroupBy does the same in one expression.

Thread safety

Dictionary<TKey, TValue> supports any number of concurrent readers, but not a writer running at the same time as anything else. Concurrent writes can corrupt its internal state, and the symptoms (lost entries, or a thread spinning at 100% CPU) are hard to trace. For shared data, use ConcurrentDictionary<TKey, TValue> and its GetOrAdd and AddOrUpdate methods.

The legacy Hashtable

This is the original example, using System.Collections.Hashtable:

using System.Collections;

Hashtable ht = new Hashtable();
ht.Add("key1", "Value1");
ht.Add("key2", "Value2");
ht.Add("key3", "Value3");

bool hasKey1 = ht.ContainsKey("key1");
bool hasValue1 = ht.ContainsValue("Value1");

foreach (DictionaryEntry de in ht)
{
    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}

The differences that matter when you maintain or migrate this code:

  • Keys and values are object. Value types get boxed, and reading a value needs a cast that can fail at run time.
  • Enumeration yields DictionaryEntry, not KeyValuePair<TKey, TValue>.
  • Reading a missing key with ht["missing"] returns null instead of throwing. Code that relies on this will start throwing KeyNotFoundException after a straight swap to Dictionary, so replace those reads with TryGetValue.
  • Hashtable is documented as safe for many readers and one writer at the same time, which Dictionary is not. If the old code depends on that, move to ConcurrentDictionary rather than Dictionary.
  • The enumeration order of a Hashtable is effectively random and differs from a Dictionary holding the same data.

Hashtable is not marked obsolete, but Microsoft recommends Dictionary<TKey, TValue> for new development.

Related examples

Leave a Comment