What are the differences b/w Hashtable, Dictionary and KeyValuePair?

Nikhil Agrawal picture Nikhil Agrawal · Apr 16, 2012 · Viewed 18.6k times · Source

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?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Apr 16, 2012

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.