.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):
Sample code
Code samples are taken from MSDN documentation and adjusted to better explain the context.
HashTable
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
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 little, but very important differences between those two.
Boxing and un-boxing
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
support 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.
Summary
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 same problems. As usually in programming, a lot depends on the context. In most cases Dictionary
is sufficient, but sometimes HashTable
just suits better.