Difference between Hashtable and Dictionary in C#
Hashtable and Dictionary are collection of data structures to hold data as key-value pairs. Dictionary is generic type, hash table is not a generic type. The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable. The Dictionary class is a strongly types < T Key, T Value > and you must specify the data types for both the key and value.
Hashtable:
Hashtable computes a hash of each key that you add and then uses this hash code to look up the element quickly.It is slower than the generic Dictionary type.
class Program
{
static Hashtable GetHashtable()
{
// Create and return new Hashtable.
Hashtable hashtable = new Hashtable();
hashtable.Add("CodeHunger", 1);
hashtable.Add("HashtableEx", 2);
return hashtable;
}
public static void Main()
{
Hashtable hashtable = GetHashtable();
// See if the Hashtable contains this key.
Console.WriteLine(hashtable.ContainsKey("HashtableEx"));
// Test the Contains method. It works the same way.
Console.WriteLine(hashtable.Contains("CodeHunger"));
// Get value of CodeHunger with indexer.
int value = (int)hashtable["CodeHunger"];
// Write the value of Area.
Console.WriteLine(value);
}
}
Dictionary:
A Dictionary class is a data structure that represents a collection of keys and values pair of data.
The key is identical in a key-value pair and it can have at most one value in the dictionary, but a value can be associated with many different keys.
This class is defined in the System.Collections.Generic namespace.
Syntax:
Dictionary<TKey,TValue>
Parameters:
TKey:Type of keys in Dictionary
Tvalue:Type of Values in Dictionary
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"CodeHunger", 2}, {"DictionaryEx", 1}};
// Loop over pairs with foreach
foreach (KeyValuePair<string, int> pair in d)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
foreach (var pair in d)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
Console.ReadKey();
}
}
Dictionary:
- – Dictionary is a generic type which means we can use it with any data type.
- – Only public static members are thread safe.
- – It returns error if we try to find a key which does not exist.
- – It is faster than a Hashtable because there is no boxing and unboxing.
Hashtable:
- – Hashtable is not a generic type.
- – All the members in a Hashtable are thread safe.
- – It returns null if we try to find a key which does not exist.
- – It is slower than dictionary because it requires boxing and unboxing.