Abstract
Hope it will give you a clear and lucid explanation of hash table and dictionary.
HashTable
Hashtable optimizes lookups. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type.
Example
- using System.Collections;
- class Program
- {
- static Hashtable GetHashtable()
- {
-
- Hashtable hashtable = new Hashtable();
- hashtable.Add("Area", 1000);
- hashtable.Add("Perimeter", 55);
- hashtable.Add("Mortgage", 540);
- return hashtable;
- }
- public static void Main()
- {
- Hashtable hashtable = GetHashtable();
-
- Console.WriteLine(hashtable.ContainsKey("Perimeter"));
-
- Console.WriteLine(hashtable.Contains("Area"));
-
- int value = (int)hashtable["Area"];
-
- Console.WriteLine(value);
- }
- }
Output
True
True
1000
DICTIONARY
Fast lookups are critical. The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings. Dictionary requires a special syntax form.
Dictionary is used when we have many different elements. We specify its key type and its value type. It provides good performance.
Example
- class DictionaryDemo
- {
- static void Main()
- {
-
- Dictionary<string, int> d = new Dictionary<string, int>()
- {
- {"Lion", 2}, {"dog", 1}};
-
- 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();
- }
- }
- }
-
Difference between Hash Table and Dictionary
Dictionary: - It returns error if we try to find key which is not exist.
- It is faster than Hash Table because there is no boxing and unboxing.
- Only public static members are thread safe.
- Dictionary is a generic type it means we can use it with any data type.
Hash Table:
- It returns Null if we try to find a key which is not exist.
- It is slower than dictionary because It require boxing and unboxing.
- All the members in Hash Table are thread safe.
- Hash Table is not generic type.