How to use C# HashTable Class
The Hashtable class in C# is a collection that represents a set of key/value pairs. It provides a mapping mechanism where keys are associated with corresponding values. This class is part of the System.Collections namespace.
With a Hashtable, you can store and retrieve data based on unique keys. Any non-null object can be used as a key, allowing for flexibility in the types of keys used. However, the values stored in the Hashtable can be of any type, including null.
Let's explore how to work with a Hashtable in C#:
First, import the System.Collections namespace:
Next, create an instance of the Hashtable class:
To add key/value pairs to the Hashtable, you can use the Add() method:
In this example, we added three key/value pairs to the Hashtable. Note that both keys and values are treated as objects.
To retrieve values from the Hashtable, you can use the indexer and provide the key:
Since the values are stored as objects in the Hashtable, you need to explicitly cast them to the appropriate types when retrieving them.
C# Hashtable | useful methods and properties
Hashtable also provides several useful methods and properties. Here are a few examples:
ContainsKey: Checks if the Hashtable contains a specific key.The following source code shows some important operations in a HashTable
Full Source C#When you execute this C# program it will add seven entries in the hashtable. The first message it will display the item 5. Then it check the value "TueDay" is existing or not . Next it remove the third item from HashTable. Finaly it displays all items exist in the HashTable.