Member-only story

C# Hashtable with Example

Shahzad Aslam
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.

C# Hashtable with Examples

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"];

Removing Key-Value Pairs:

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

Responses (1)