Open In App

C# Hashtable Class

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

Hashtable class in C# is a part of the operations. It represents a collection of key-value pairs that are organized based on the hash code of the key. The Hashtable class provides various types of methods that are used to perform different types of operations on the hashtables. In Hashtable, keys are used to access the elements present in the collection. For very large Hashtable objects, we can increase the maximum capacity to 2 billion elements on a 64-bit system.

  • In Hashtable, a key cannot be null but the value can be.
  • In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable.
  • The capacity of a Hashtable is the number of elements that Hashtable can hold.
  • A hash function is provided by each key object in the Hashtable.

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

C#
// C# Program to demonstrates Hashtable
using System;
using System.Collections;

class Geeks {
    static void Main()
    {
        // Create a Hashtable of string 
        // keys and integer values
        Hashtable ht = new Hashtable();

        // Adding elements to the Hashtable
        ht.Add("One", 1);
        ht.Add("Two", 2);
        ht.Add("Three", 3);

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

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

Declaration of Hashtable

In C#, the Hashtable is declared as:

Hashtable ht = new Hashtable();

Constructors

ConstructorDescription
Hashtable()

Initalizes a new, empty instance with default parameters (initial capacity, load factor, etc.).

Hashtable(IDictionary)Copies elements from the specified dictionary to a new Hashtable with default parameters
Hashtable(IDictionary, IEqualityComparer)Copies elements from the specified dictionary to a new Hashtable and uses the provided IEqualityComparer
Hashtable(Int32)Initializes a new, empty instance with a specified initial capacity and default parameters.
Hashtable(Int32, Single)Initializes a new, empty instance with a specified initial capacity and load factor.
Hashtable(Int32, Single, IEqualityComparer)Initializes a new, empty instance with a specified initial capacity, load factor, and IEqualityComparer
Hashtable(SerializationInfo, StreamingContext)Initalizes a new instance from serialized data (for deserialization purposes).

Example: This example demonstrates how to create and initialize two Hashtable objects, insert key-value pairs and print the mappings.

C#
// Using Hashtable() Constructor
using System;
using System.Collections;

class Geeks {
    static void Main()
    {
        // Initialize Hashtable
        Hashtable ht1 = new Hashtable();
        Hashtable ht2 = new Hashtable();

        // Inserting elements using Add() method
        ht1.Add(1, "one");
        ht1.Add(2, "two");
        ht1.Add(3, "three");

        ht2.Add(4, "four");
        ht2.Add(5, "five");
        ht2.Add(6, "six");

        // Print mappings to the console
        Console.WriteLine("Mappings of ht1: ");
        foreach(DictionaryEntry i in ht1)
        {
            Console.WriteLine($"{i.Key} - {i.Value}");
        }

        Console.WriteLine("Mappings of ht2: ");
        foreach(DictionaryEntry i in ht2)
        {
            Console.WriteLine($"{i.Key} - {i.Value}");
        }
    }
}

Output
Mappings of ht1: 
3 - three
2 - two
1 - one
Mappings of ht2: 
6 - six
5 - five
4 - four

Properties

PropertiesDescription
comparerGets or sets the IComparer to use for the Hashtable.
CountGets the number of key/value pairs contained in the Hashtable.
EqualityComparerGets the IEqualityComparer to use for the Hashtable.
hcpGets or sets the object that can dispense hash codes.
IsFixedSizeGets a value indicating whether the Hashtable has a fixed size.
IsReadOnlyGets a value indicating whether the Hashtable is read-only.
IsSynchronizedGets a value indicating whether access to the Hashtable is synchronized (thread safe).
Item[Object]Gets or sets the value associated with the specified key.
KeysGets an ICollection containing the keys in the Hashtable.
SyncRootGets an object that can be used to synchronize access to the Hashtable.
ValuesGets an ICollection containing the values in the Hashtable.

Example: This example demonstrates how to use the IsSynchronized property check if a Hashtable is thread-safe and the Count property to get the number of elements in a Hashtable.

C#
// C# program to demonstrates the use 
// of IsSynchronized and Count property
using System;
using System.Collections;

class Geeks {

    static void Main(string[] args)
    {

        // create and initialize Hashtable using Add() method
        Hashtable h1 = new Hashtable();
        h1.Add("1", "Welcome");
        h1.Add("2", "to");
        h1.Add("3", "geeks");
        h1.Add("4", "for");
        h1.Add("5", "geeks");


        // Creating a synchronized packing around the Hashtable
        Hashtable h2 = Hashtable.Synchronized(h1);

        // print the status of both Hashtables
        Console.WriteLine("h1 Hashtable is {0}.",
                h1.IsSynchronized ? "synchronized" : "not synchronized");

        Console.WriteLine("h2 Hashtable is {0}.",
                h2.IsSynchronized ? "synchronized" : "not synchronized");

        // Using Count Property
        Console.WriteLine("Total Number of Elements in h1: " + h1.Count);
    }
}

Output
h1 Hashtable is not synchronized.
h2 Hashtable is synchronized.
Total Number of Elements in h1: 5

Methods

MethodDescription
Add(Object, Object)Adds an element with the specified key and value into the Hashtable.
Clear()Removes all elements from the Hashtable.
Clone()Creates a shallow copy of the Hashtable.
Contains(Object)Determines whether the Hashtable contains a specific key.
ContainsKey(Object)Determines whether the Hashtable contains a specific key.
ContainsValue(Object)Determines whether the Hashtable contains a specific value.
CopyTo(Array, Int32)Copies the Hashtable elements to a one-dimensional Array instance at the specified index.
Equals(Object)Determines whether the specified object is equal to the current object.
GetEnumerator()Returns an IDictionaryEnumerator that iterates through the Hashtable.
GetHashCode()Serves as the default hash function.
GetObjectData(SerializationInfo, StreamingContext)Implements the ISerializable interface and returns the data needed to serialize the Hashtable.
GetType()Gets the Type of the current instance.
Remove(Object)Removes the element with the specified key from the Hashtable.
Synchronized(Hashtable)Returns a synchronized (thread-safe) wrapper for the Hashtable.
ToString()Returns a string that represents the current object.

Example:

C#
// C# program to demonstrate the working of Add()
// and Remove() Methods
using System;
using System.Collections;

class Geeks {

    static void Main(string[] args)
    {
        // create and initialize Hash table
        // using Add() method
        Hashtable ht = new Hashtable();
        ht.Add("1", "Geek1");
        ht.Add("2", "Geek2");
        ht.Add("3", "Geek3");
        ht.Add("4", "Geek4");
        ht.Add("5", "Geek5");

        ICollection k = ht.Keys;

        Console.WriteLine("Hashtable Contains:");

        foreach(var i in k)
        {
            Console.WriteLine(i + "-" + ht[i]);
        }

        Console.WriteLine();

        // Remove element 4
        // using Remove() method
        ht.Remove("4");
        ht.Remove("5");

        // printing updated Hash table
        Console.WriteLine("Hashtable after removing element 4:");

        foreach(var i in k)
        {
            Console.WriteLine(i + "-" + ht[i]);
        }
    }
}

Output
Hashtable Contains:
3-Geek3
5-Geek5
4-Geek4
2-Geek2
1-Geek1

Hashtable after removing element 4:
3-Geek3
2-Geek2
1-Geek1


Next Article

Similar Reads