Difference between Hashtable and Dictionary

Posted By : Bipul Kumar Tiwari,

Hashtable and Dictionary are collection of data structures to hold data as key-value pairs. Dictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out. The major difrance are:

Hashtable Dictionary
Hashtable is a weakly type data structure. Dictionary class is a strongly type data structure.
You can add keys and values of any Object Type to the Hashtable. You must specify the data types for both the key and value to Dictionary .
Hashtable returns null if we try to find a key which does not exist. Dictionary throws an exception (KeyNotFoundException) if we try to find a key which does not exist.
Hashtable is thread safe. Dictionary is not thread safe..
Hashtable is slower, because it requires boxing and unboxing.. Dictionary is faster, because there is no boxing and unboxing.

Hashtable Example:

Hashtable objHash = new Hashtable();
objHash.Add(4, 200); // Key is int
objHash.Add(1, 200); // Key is int
objHash.Add(1.1, 400); // Key is float
objHash.Add('A', 600); // Key is char
objHash.Add("Test", 800); // Key is string
For display the value:
lblMsg1.Text = objHash[4].ToString();
lblMsg2.Text = objHash[1].ToString();
lblMsg3.Text = objHash[1.1].ToString();
lblMsg4.Text = objHash['A'].ToString();
lblMsg5.Text = objHash["Test"].ToString();

Dictionary Example:

Dictionary< int, string> dictionary = new Dictionary< int,string>();
dictionary.Add(-1, "Priyanka");
For display the value:
foreach (KeyValuePair p in dictionary)
lblDisplay.Text = p.Value + " " + lblDisplay.Text;

Related Articles


About the Author

Its me BIPUL who is logically minded creative at heart , a good communicator , a self taught full stack developer. I constantly focuses on my thinking , reading , collecting and creating my work in a order to enhance my skills.

I discover new dimensions for growing bussiness with a proven record in creating database and programming. I have a strong technical skills as well as strong interpersonal skills. Read more...

Browse By Category

Popular Articles