Difference between Hashtable and Dictionary in C#


C# Collection Hashtable and Dictionary: Here in this article, will understand the difference between hashtable and dictionary in C#. But first, let understand what is collection in C#. The collection is a set of the related object. And unlike an array, the Collection can grow and shrink dynamically as the number of objects gets added or deleted based on our requirement.

In .NET Framework, we can classify collections into two categories .i.e Generic Collection and Non-Generic Collection.

In Generic Collection we have List<T>, Dictionary<TKey,TValue>, SortedList<T>, Stack<T>, Queue<T>. Whereas in Non-Generic Collection we have ArrayList, Hashtable, SortedList, Stack, Queue.

Below is the list of differences between Hashtable and Dictionary:

A Hashtable is under the non-generic collection category. 
A Dictionary is under the generic collection category.
System.Collections namespace is used to access Hashtable.
System.Collections.Generic namespace is used to access Dictionary, as it's a generic collection.
Hashtable represents a collection of objects, which are stored in Key / Value pair of the same type or of different type.
Dictionary represents a collection of objects, which are also stored in Key/Value pair but with the only same type.
In Hashtable, while retrieving an element from the collection, it needs to be typecasting.
In Dictionary, there is no need for typecasting or boxing/ unboxing.
In Hashtable it returns null values, if we access a key that is not present in the collection.
Whereas Dictionary throws an error, is we access a key that is not present in the collection.
Hashtable is slower as compared to Dictionary, due to boxing and unboxing while retrieving elements.
Dictionary is faster as compared to Hashtable.

Hope you understand the difference between Hashtable and Dictionary in C#

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

Post Comment

Your email address will not be published. Required fields are marked *