Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Learn Hashtable in C# with example

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#

Method Description
Add Adds an item with a key and value into the hashtable.
Contains Checks whether the hashtable contains a specific key
Remove Removes the item with the specified key from the hashtable
Clear Removes all the items from the hashtable.
ContainsKey Checks if hashtable contains a specific key.
ContainsValue Checks if the hashtable contains a specific value.

Useful Propertis of Hashtable in C#

Properties Description
IsReadOnly Gets boolean value indicating whether the Hashtable is read-only.
Item Gets or sets the value associated with the specified key.
Keys Gets an ICollection of keys in the Hashtable.
Values Gets an ICollection of values in the Hashtable.
Count 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(2, 2.2);
htObj.Add(3, true);
htObj.Add(4, DateTime.Now);
htObj.Add(5, null);
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[1];
Console.WriteLine(strValue1);

DateTime? strValue4 = (DateTime?)htObj[4];
Console.WriteLine(strValue4);

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]);
}
c# hashtable example

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#


 
Learn Hashtable in C#
C# Tutorial
Learn C# Online Tutorial


Group Training