HashMap in C#

Minahil Noor Dec 21, 2022 Mar 09, 2021 Csharp
HashMap in C#

This article will introduce a hashmap equivalent in C#.

Use the Dictionary Collection as Hashmap Equivalent in C#

We will use the Dictionary collection as hashmap equivalent in C#. It represents a collection of key-value pairs. The key-value pair means that every value has a key. The correct syntax to create a dictionary is as follows.

IDictionary<type, type> numberNames = new Dictionary<type, type>();

There are multiple methods to perform operations on the created dictionary such as Add(), Clear(), ContainsKey(), ContainsValue(), Equals(), GetType(), Remove(), etc.

The program below shows how we can add elements to the dictionary.

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
IDictionary<int, string> flowerNames = new Dictionary<int, string>();

foreach(KeyValuePair<int, string> kvp in flowerNames)
    Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);


Key: 1, Value: Rose
Key: 2, Value: Jasmine
Key: 3, Value: Lili

There are some limitations to the Dictionary collection. We cannot add null keys to it. If we do, then it will throw ArgumentNullException.