Open In App

C# Hashtable

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, a Hashtable is a collection that stores key-value pairs. It uses a hash code to organize the keys for efficient data retrieval. The key can be any object, and each key is associated with a corresponding value. It is a part of the System.Collections namespace and is non-generic (which means it can store any kind of object as both the key and value).

  • In Hashtable, the key cannot be null, but the value can be null.
  • In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable.
  • Hashtable can store elements of different types.
  • In the Hashtable key must be unique, duplicated keys are not allowed.
  • The elements of Hashtable that are key-value pair is stored as DictionaryEntry objects.

Example: This example demonstrates how to create a Hashtable, add key-value pairs to it, and iterate over the entries to display the content.

C#
// C# program to add elements to the hashtable
using System;
using System.Collections;

class Geeks {
    static void Main()
    {
        // Create a new Hashtable
        Hashtable ht = new Hashtable();

        // Add key-value pairs to the Hashtable
        ht.Add("One", 1);
        ht.Add("Two", 2);
        ht.Add("Three", 3);

        Console.WriteLine("Hashtable elements:");
        foreach(DictionaryEntry e in ht)
        {
            Console.WriteLine($"{e.Key}: {e.Value}");
        }
    }
}

Output
Hashtable elements:
Two: 2
Three: 3
One: 1

Creating a Hashtable

In C#, the Hashtable class offers 16 different constructors each with its own use. For simplicity, we will focus on the most commonly used constructor which is Hashtable().

Hashtable(): This constructor is used to create an instance of the Hashtable class which is empty and has the default initial capacity, load factor, hash code provider, and compare.

Let’s see how to create a Hashtable using Hashtable() constructor:

Step1: Include the System.Collections namespace in your program with the help of using keyword.

using System.Collections;

Step 2: Use the Hashtable() constructor to create an empty Hashtable.

Hashtable ht = new Hashtable();

Performing Different Operations on Hashtable

1. Adding Elements: We can add elements in the Hashtable using Add() method.

Example: Here, this program demonstrates how to create and add elements to the Hashtable.

C#
// Add Elements in Hashtable
using System;
using System.Collections;

class Geeks {

    // Main Method
    static public void Main()
    {
        // Create a hashtable using the Hashtable class
        Hashtable h1 = new Hashtable();

        // Adding key/value pairs using Add() method
        h1.Add("1", "Welcome");
        h1.Add("2", "to");
        h1.Add("3", "GeeksforGeeks");

        Console.WriteLine("Key and Value pairs from h1:");
      
        // Iterating through the hashtable using
        // DictionaryEntry
        foreach(DictionaryEntry ele1 in h1)
        {
            Console.WriteLine("{0} and {1}", ele1.Key,
                              ele1.Value);
        }

        // Create another hashtable using the Hashtable
        // class and a collection initializer
        Hashtable h2 = new Hashtable() {
            { 1, "hello" }, { 2, 234 }, { 3, 230.45 },
            {
                4, null
            }
        };

        Console.WriteLine(
            "Key and Value pairs from h2:");
      
        // Iterating through the hashtable using the Keys
        // collection
        foreach(var ele2 in h2.Keys)
        {
            Console.WriteLine("{0} and {1}", ele2,
                              h2[ele2]);
        }
    }
}

Output
Key and Value pairs from h1:
3 and GeeksforGeeks
2 and to
1 and Welcome
Key and Value pairs from h2:
4 and 
3 and 230.45
2 and 234
1 and hello

2. Removing Elements: The Hashtable class provides two different methods to remove elements and the methods are:

  • Clear(): This method is used to remove elements from the Hashtable.
  • Remove(): This method is used to remove elements from the specified key.

Example: This example demonstrates how to create a Hashtable, add key-value pairs and clear all the elements from the Hashtable.

C#
// Remove Elements from Hashtable
using System;
using System.Collections;

class Geeks {

    // Main Method
    static public void Main()
    {

        // Create a hashtable
        // Using Hashtable class
        Hashtable h1 = new Hashtable();

        // Adding key/value pair
        // in the hashtable
        // Using Add() method
        h1.Add("1", "Welcome");
        h1.Add("2", "to");
        h1.Add("3", "GeeksforGeeks");

        // Using remove method
        // remove A2 key/value pair
        h1.Remove("2");

        Console.WriteLine("Key and Value pairs :");

        foreach(DictionaryEntry e1 in h1)
        {
            Console.WriteLine("{0} and {1} ", e1.Key,
                              e1.Value);
        }

        // Before using Clear method
        Console.WriteLine("Total number of elements present"
                              + " in h1:{0}",
                          h1.Count);

        h1.Clear();

        // After using Clear method
        Console.WriteLine(
            "Total number of elements present in"
                + " h1:{0}",
            h1.Count);
    }
}

Output
Key and Value pairs :
3 and GeeksforGeeks 
1 and Welcome 
Total number of elements present in h1:2
Total number of elements present in h1:0

3. Checking the Availability of Elements in the Hashtable: Hashtable class provides three methods to check if the element is present in the hashtable or not.

  • Contains(): This method is used to check if a specific key or value exists in the Hashtable.
  • ContainsKey(): This method is used to check if the specified key exists in the HashTable.
  • ContainsValue(): This method is used to check if a specified value exists in the Hashtable.

Example: This example demonstrates how to check the presence of a key or value in a Hashtable using the Contains(), ContainsKey() and ContainsValue() method.

C#
// C# program to illustrate how
// to check key/value present
// in the hashtable or not
using System;
using System.Collections;

class Geeks {

    // Main Method
    static public void Main()
    {

        // Create a hashtable
        // Using Hashtable class
        Hashtable ht = new Hashtable();

        // Adding key/value pair in the hashtable
        // Using Add() method
        ht.Add("1", "Welcome");
        ht.Add("2", "to");
        ht.Add("3", "GeeksforGeeks");

        // Determine whether the given
        // key present or not
        // using Contains method
        Console.WriteLine(ht.Contains("3"));
        Console.WriteLine(ht.Contains(12));
        Console.WriteLine();

        // Determine whether the given
        // key present or not
        // using ContainsKey method
        Console.WriteLine(ht.ContainsKey("1"));
        Console.WriteLine(ht.ContainsKey(1));
        Console.WriteLine();

        // Determine whether the given
        // value present or not
        // using ContainsValue method
        Console.WriteLine(ht.ContainsValue("geeks"));
        Console.WriteLine(ht.ContainsValue("to"));
    }
}

Output
True
False

True
False

False
True

4. Updating the Hashtable: In C#, the Hashtable class does not provide a direct method to update the value of an existing key. But we can achieve the update by following these steps:

  • Check if the key exists in the Hashtable using the ContainsKey method.
  • If the key exists, retrieve the current value using the key and store it in a variable.
  • Assign the new value to the key in the Hash table using the same key.
  • Optionally, remove the old key/value pair if needed.

Example: This example demonstrates how to update the value of an existing key in a Hashtable and print the updated key-value pairs.

C#
// C# Program to demonstrates how to update the hashtable
using System;
using System.Collections;

class Geeks {
    static void Main()
    {
        // Create a new Hashtable
        Hashtable ht = new Hashtable();

        // Add some key-value pairs
        ht.Add("key1", "value1");
        ht.Add("key2", "value2");

        // Updating the value of an existing key
        string s = "key1";
        if (ht.ContainsKey(s)) {
            ht[s] = "s1";
        }

        // Accessing the updated value
        string s1 = (string)ht[s];
        Console.WriteLine("Updated value: " + s1);

        // Print all key-value pairs in the ht
        foreach(DictionaryEntry e in ht)
        {
            Console.WriteLine("Key: " + e.Key
                              + ", Value: " + e.Value);
        }
    }
}

Output
Updated value: s1
Key: key1, Value: s1
Key: key2, Value: value2


Next Article

Similar Reads