Member-only story
C# Hashtable with Example
2 min readMay 5, 2024
The HashTable is related to System.Collections namespace. The HashTable contains on key-value pairs. Where each key is associated with a unique value.
Features with hashtable in C#:
Creating a HashTable:
You will use System.Collections namespace for creating The hashtable. The below code is syntax of creating the hashtable.
Example
using System.Collections;
Hashtable fruittable = new Hashtable();
Adding Key-Value Pairs:
A HashTable contains the key-value pairs and for making key-value pairs you can use Add method. The key must be unique in each key-value pairs in Add method.
Example
fruittable.Add("FruitName", "Apple");
fruittable.Add("FruitPrice", 20);
fruittable.Add("FruitColor", "Red");
Accessing Values:
You can retrieve values by their associated keys:
Example
string fruitname = (string)fruittable["FruitName"];
int fruitprice = (int)fruittable["FruitPrice"];
string fruitcolor = (string)fruittable["FruitColor"];