Reader Level:
ARTICLE

Hashtable in C#

On November 14, 2005 Articles | How do I
Hashtable is useful when you need to store data in a key and value pair. This article shows how to use hashtable in C#.
  • 0
  • 0
  • 376367

This quick how do I shows how to use a Hashtable in C#.

Creating a Hashtable

The Hashtable class in C# represents a hashtable. The following code creates a Hashtable:

private Hashtable hshTable = 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 three items to hashtable.

hshTable .Add("Author1",  "Mahesh Chand");
hshTable .Add("Author2",  "James Brand");
hshTable .Add("Author3",  "Mike Gold");

Retrieving an Item Value from Hashtable

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

string name = hshTable["Author1"].ToString();

Removing Items from a Hashtable

The Remove method removes an item from a Hashtable. The following code removes item with index "Author1" from the hashtable:

hshTable.Remove("Author1");

Looking through all Items of a Hashtable

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

// Loop through all items of a Hashtable
IDictionaryEnumerator en = hshTable.GetEnumerator();
while (en.MoveNext())
{
      string str = en.Value.ToString();
}

Mahesh Chand

Mahesh Chand is founder of C# Corner. C# Corner founded in 1999 is a FREE member contributions based open platform for developers to solve problems, learn new technology and hang out.  M...

  • 1rank
  • 71M readers
  • 9times
COMMENT USING

Trending up