Abstract
Hope it will give you a clear and lucid explanation of the 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()
{
// Create and return new Hashtable.
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();
// See if the Hashtable contains this key.
Console.WriteLine(hashtable.ContainsKey("Perimeter"));
// Test the Contains method. It works the same way.
Console.WriteLine(hashtable.Contains("Area"));
// Get value of Area with indexer.
int value = (int)hashtable["Area"];
// Write the value of 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. A dictionary requires a special syntax form.
The 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()
{
// Example Dictionary again
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"Lion", 2}, {"dog", 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();
}
}
Difference between Hash Table and Dictionary
Dictionary
- It returns an error if we try to find the key which does not exist.
- It is faster than Hash Table because there is no boxing and unboxing.
- Only public static members are thread-safe.
- A 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 that does not exist.
- It is slower than a dictionary because It requires boxing and unboxing.
- All the members in the Hash Table are thread-safe.
- Hash Table is not a generic type.