I use Dictionary in my code but my colleagues use Hashtable. MSDN says they work on Key Value pair & examples of Hashtable and dictionary are same on MSDN.
Then how different are they from each other & which is the best of them or are they suited for difference occasions?
In Hashtable, you can store key/value pairs of the same type or of the different type. In Dictionary, you can store key/value pairs of same type. In Hashtable, there is no need to specify the type of the key and value. In Dictionary, you must specify the type of key and value.
Hashtable is included in the namespace called Collections while Dictionary is included in the namespace called System. Collections. Generic namespace. Hashtable is non-generic so it can be a collection of different data types and Dictionary belongs to a generic class so it is a collection of specific data types.
Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.
Dictionary is a generic type and returns an error if you try to find a key which is not there. The Dictionary collection is faster than Hashtable because there is no boxing and unboxing.
Hashtable
is an untyped associative container that uses DictionaryEntry
class to return results of enumeration through its key-value pairs.
Dictionary<K,T>
is a generic replacement of Hashtable
that was introduced in C# 2.0. It uses KeyValuePair<K,T>
generic objects to represent its key-value pairs.
The only place where you should see Hashtable
these days is legacy code that must run on .NET 1.1, before generics have been introduced. It's been kept around for compatibility reasons, but you should prefer Dictionary<K,T>
whenever you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With