Skip to content
Code On!

Dictionary And HashTable In C#

Dictionary And HashTable In C#

1min read

.NET Framework provides several data structures for constant O(1) access. In software engineering we call them lookup tables. In .NET we can list following lookup-tables (at least):

Code samples are taken from MSDN documentation and adjusted to better explain the context.

Hashtable openWith = new Hashtable();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
openWith.Add(123, "cmd.exe");

Dictionary<string, string> openWith = new Dictionary<string, string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
openWith.Add(123, "cmd.exe"); //this will throw exception

As we can see the code looks pretty similar. Although there are few, but very important differences between those two.

Dictionary is a generic type. This is super important when performance comes into play. Accessing HashTable items of primitive types requires extra un-boxing operation. In Dictionary this can be omitted.

Generic nature of a Dictionary gives us also type-safety out of the box, so the possibility of inserting a wrong type in the data structure is limited. On the other hand HashTable supports multiple reader threads. Dictionary is not thread-safe. .NET 4.0 introduces ConcurrentDictionary (with a slightly different interface) that is thread safe.

HashTable will also return null if key does not exist. Dictionary will throw an exception in that case.

The intention of this post was to point out differences between very similar structures in .NET. Both HashTable and Dictionary can be used to solve the same problems. As usual in programming, a lot depends on the context. In most cases Dictionary is sufficient, but sometimes HashTable just suits better.