Member-only story
Hi everyone, welcome back. In these examples, we will be going over Hashtables in C#. Hashtables can be used to store a collection of data, similar to that of a normal list. The main difference is that a Hashtable can store elements as key/value pairs as an alternative to using index numbers. The keys must be unique and cannot be null. The values can be duplicates or be null. With this introduction out of the way, let’s get into it.
Creating Hashtables
Let’s start by creating a Hashtable. Before we can create a Hashtable, we need to make sure that we have our Hashtable import, which is included within the System.Collections package:
using System.Collections;
Now, we can successfully create our Hashtable:
Hashtable myHT = new Hashtable();
We have created our Hashtable and named it ‘myHT’.
Adding Elements Into The HashTable
Now, let’s see how we can add elements into the Hashtable. We can do this by using the built in Add() function that is provided. Let’s see an example:
Hashtable myHT = new Hashtable();
myHT.Add(1, "One");
myHT.Add(4, "Four");
myHT.Add(17, "Seventeen");
foreach(var key in myHT.Keys)
{
Console.WriteLine(key + ": " +…