What is Hashtable in C#?
Hashtable in C# is a collection object that comes under System.Collections namespace, Hashtable is similar to generic Dictionary collection
Useful Methods of Hashtable in C#
||Adds an item with a key and value into the hashtable.
||Checks whether the hashtable contains a specific key
||Removes the item with the specified key from the hashtable
||Removes all the items from the hashtable.
||Checks if hashtable contains a specific key.
||Checks if the hashtable contains a specific value.
Useful Propertis of Hashtable in C#
||Gets boolean value indicating whether the Hashtable is read-only.
||Gets or sets the value associated with the specified key.
||Gets an ICollection of keys in the Hashtable.
||Gets an ICollection of values in the Hashtable.
||Gets the total count of keys in the Hashtable.
How to write Hashtable in C#
Remember that hashtable works on key/value combination, key or value can be of any data type, look at the example below, this is how we can add key/value to Hashtable
Hashtable htObj = new Hashtable();
htObj.Add(1, "This is string");
htObj.Add("Six", "see the key difference");
Now you see how to retrieve value from hashtable
, As you have seen that hashtable store values with key, so you can retrieve value using same key
string strValue1 = (string)htObj;
DateTime? strValue4 = (DateTime?)htObj;
As you have seen that a Hashtable can contains a key and a value of any data type. So while casting, values must be cast to an appropriate data type otherwise it will give compile-time error.
Notice in above example while retrieving data from hashtable, one converted to string and four converted to datetime
C# Hashtable Best Practice
Now we have seen that in hashtable we can have different data type for key and values both field, but ideally we should have only same data type for key fields.
Now let’s try to read all the key values of above hashtable dynamically, htObj.Keys
will get all the keys
foreach (int key in htObj.Keys)
Console.WriteLine("Key: " + key + " Value: " + htObj[key]);
See the error for last key, which is a different data type, when all keys are integer and the last (six) key is a string
So, remember to keep all the keys of same data type while creating a hashtable in C#