blog

Home / DeveloperSection / Blogs / Hashtable in C#

Hashtable in C#

Hashtable in C#

Uttam Misra 5221 18-May-2012

How to use a Hashtable in C#.

Creating a Hashtable

The following code creates a Hashtable:

private Hashtable hsTable = new Hashtable();

Adding Items to a Hashtable
Add method of Hashtable is used to add items to the hashtable. The
method has index and value parameters.

The following code adds items to hashtable.

hsTable .Add("Game1",  "Cricket");
hsTable.Add("Game2",  "Football");
hsTable.Add("Game3",  "Badminton");
hsTable.Add("Game3",  "Basketball");
hsTable.Add("Game3",  "Tennis");

Retrieving an Item Value from Hashtable

The following code returns the value of "Cricket" key:

string name = hsTable ["Cricket "].ToString();

Removing Items from a Hashtable

The Remove method removes an item from a Hashtable.

The following code removes item with index "Cricket" from the hashtable:

hsTable.Remove("Cricket");

Looking through all Items of a Hashtable

The following code loops through all items of a hashtable and reads the values.


IDictionaryEnumerator en = hsTable.GetEnumerator(); while (en.MoveNext())
{
      string str = en.Value.ToString();
}

 


c# c# 
Updated 11-Aug-2020
More than 18 years of working experience in IT sector. We are here to serve you best.

Leave Comment

Comments

Liked By