So I learned something very interesting today on SO from this link: Dictionary over Hashtables. I was under the impression at one point that a Hash tables was a Dictionary and that a Hashtable was better and faster. I was mistaken. I know, this doesn’t happen often.
First a HashTable is a Dictionary type. For those of you that don’t know, when one says that, basically a HashTable object inherits its core features from the Dictionary object. A Dictionary is also faster than a Hashtable and safer to use. Why you say?
Well the Dictionary is a type safe object. So what does type safe mean? Well, type safe means that when you create a reference object that instantiates that object, it requires implicit knowledge of what type of object you are going to pump into it. For instance, in the case of a dictionary, you could do something like this:
var items = new Dictionary<string, int>(); items.Add("1", 1); items.Add("2", 2); items.Add("3", 3); items.Add("4", 4); items.Add("5", 5); items.Add("6", 6); items.Add("7", 7); items.Add("8", 8); items.Add("9", 9); items.Add("10", 10); items.Add("11", 11); return new SelectList(items);
Now as you can see on the initialization of the dictionary, we are specifying two parameters, string and int. The first parameter states the type the key will be and the second defines what the value will be. With this declaration, you are giving the compiler a guarentee that this object will ONLY use those types to define the key and value. This causes 2 things.
First it makes for less development errors because no one can sneak values of different types in without causing a compiler error. If the Dictionary is not type safe, someone could put a POCO object or a primitive type other than string and int. This wouldn’t cause a compiler error if it isn’t type safe, but if you try to access the object without a cast, a runtime error would occur. This creates bugs where they shouldn’t be.
Second it provides better performance due to the lack of boxing and unboxing (casting).
HashTables are to Dictionary like ArrayList is it’s generic counter part List<T>. Lets look at a HasTable example:
Hashtable hashtable = new Hashtable(); hashtable.Add("Integer", 1); hashtable.Add("Double", 55.6); hashtable.Add("String", “What up”);
Now you will notice that I have this example set up that it shows 3 different types, int, double and string. The Hash is always string in this case. Now take this example of an attempt to use this variable.
int value = (int)hashtable["String"];
Now this is obviously a very simple example, but in this example, the code would blow up because you are assuming an integer because of the value of the first key value pair (“Integer”). This is what happens when you aren’t type safe and another developer might want to use your library. If you are the only one using it, you still might forget and cause some mayhem.
Hope this helps other with some clarification!