Hashtable in C#

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:

  1. 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.

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

Retrieving an Item Value from Hashtable

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

  1. 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:

  1. hshTable.Remove("Author1");  

Looking through all Items of a Hashtable

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

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

Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.