Collection Types - C# Dictionary and Hashtable
Differences Between Hashtable and Dictionary
The System.Collections.Hashtable class, and the System.Collections.Generic.Dictionary<TKey, TValue> implements the System.Collections.IDictionary interface. The Dictionary<TKey, TValue> generic class also implements the IDictionary<TKey, TValue> generic interface. Therefore, each element in these collections is a key-and-value pair.
- Hashtable is not a generic type.
- All the members in a Hashtable are thread safe.
- It is slower than dictionary because it requires Boxing and Unboxing.
- It returns null if we try to find a key which does not exist.
private void HashtableSample()
// Inserting values into C# Hashtable
Hashtable objHash = new Hashtable();
objHash.Add(1, 100); // using int datatype
objHash.Add(2.99, 200); // using float datatype
objHash.Add('A', 300); // using char datatype
objHash.Add("AB45", 500); // using string datatype
//c# Hashtable getting values by Key name
lblText.Text = objHash.ToString();
lblText.Text = objHash[2.99].ToString();
lblText.Text = objHash['A'].ToString();
lblText.Text = objHash["AB45"].ToString();
- Dictionary is a generic type which means we use it with any data type.
- Only public static members are thread safe.
- It is faster than a Hashtable because there is no Boxing and Unboxing.
- It returns an error if we try to find a key which doesn't exist.
C# Dictionary Examples
private void DictionarySample()
// Inserting values into C# Dictionary
Dictionary<string, int> dic = new Dictionary<string, int>();
// Getting dictionary key by value
foreach (KeyValuePair<string, int> pair in dic)
lblText.Text = pair.Key + " = " + pair.Value + " " + lblText.Text;
Conclusion: It was fun in learning and writing an article on Collection Types - C# Dictionary and Hashtable. I hope this article will be helpful for enthusiastic peoples who are eager to learn and implement some interesting stuffs in new technology.
Please feel free to comment your opinion about this article or whatever you feel like telling me. Also if you like this article, don't forget to share this article with your friends. Thanks!
Collection Types - C# Dictionary and Hashtable Reviewed by Ravi Kumar on 12:03:00 PM Rating: