C# | Hashtable Class

The Hashtable class represents a collection of key/value pairs that are organized based on the hash code of the key. This class comes under the System.Collections namespace. The Hashtable class provides various types of methods that are used to perform different types of operation on the hashtables. In Hashtable, keys are used to access the elements present in the collection. For very large Hashtable objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system.

Characteristics of Hashtable Class:

  • In Hashtable, key cannot be null but 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.

Constructors

CONSTRUCTOR DESCRIPTION
Hashtable() Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.
Hashtable(IDictionary) Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, hash code provider, and comparer.
Hashtable(IDictionary, IEqualityComparer) Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to a new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor and the specified IEqualityComparer object.
Hashtable(IDictionary, IHashCodeProvider, IComparer) Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, and the specified hash code provider and comparer. This API is obsolete. For an alternative, see Hashtable(IDictionary, IEqualityComparer).
Hashtable(IDictionary, Single) Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, and the default hash code provider and comparer.
Hashtable(IDictionary, Single, IEqualityComparer) Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor and IEqualityComparer object.
Hashtable(IDictionary, Single, IHashCodeProvider, IComparer) Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, hash code provider, and comparer.
Hashtable(IEqualityComparer) Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified IEqualityComparer object.
Hashtable(IHashCodeProvider, IComparer) Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified hash code provider and comparer.
Hashtable(Int32) Initializes a new, empty instance of the Hashtable class using the specified initial capacity, and the default load factor, hash code provider, and comparer.
Hashtable(Int32, IEqualityComparer) Initializes a new, empty instance of the Hashtable class using the specified initial capacity and IEqualityComparer, and the default load factor.
Hashtable(Int32, IHashCodeProvider, IComparer) Initializes a new, empty instance of the Hashtable class using the specified initial capacity, hash code provider, comparer, and the default load factor.
Hashtable(Int32, Single) Initializes a new, empty instance of the Hashtable class using the specified initial capacity and load factor, and the default hash code provider and comparer.
Hashtable(Int32, Single, IEqualityComparer) Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, and IEqualityComparer object.
Hashtable(Int32, Single, IHashCodeProvider, IComparer) Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, hash code provider, and comparer.
Hashtable(SerializationInfo, StreamingContext) Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to create Hashtable
using System;
using System.Collections;
  
class GFG {
  
    // Main method
    static void Main(string[] args)
    {
  
        // create and initalize Hash table
        // using Add() method
        Hashtable g = new Hashtable();
        g.Add(1, "welcome");
        g.Add(2, "to");
        g.Add(3, "tutorials");
        g.Add(4, "of");
        g.Add(5, "C#");
  
        ICollection key = g.Keys;
  
        // Print Hash table
        Console.WriteLine("Hashtable:");
        Console.WriteLine();
        foreach(var val in key)
        {
            Console.WriteLine(val + "-" + g[val]);
        }
    }
}

chevron_right


Output:

Hashtable:

5-C#
4-of
3-tutorials
2-to
1-welcome

Properties

PROPERTY DESCRIPTION
comparer Gets or sets the IComparer to use for the Hashtable.
Count Gets the number of key/value pairs contained in the Hashtable.
EqualityComparer Gets the IEqualityComparer to use for the Hashtable.
hcp Gets or sets the object that can dispense hash codes.
IsFixedSize Gets a value indicating whether the Hashtable has a fixed size.
IsReadOnly Gets a value indicating whether the Hashtable is read-only.
IsSynchronized Gets a value indicating whether access to the Hashtable is synchronized (thread safe).
Item[Object] Gets or sets the value associated with the specified key.
Keys Gets an ICollection containing the keys in the Hashtable.
SyncRoot Gets an object that can be used to synchronize access to the Hashtable.
Values Gets an ICollection containing the values in the Hashtable.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate the
// Properties of Hashtable
using System;
using System.Collections;
  
class GFG {
  
    // Main method
    static void Main(string[] args)
    {
  
        // create and initalize Hash table
        // using Add() method
        Hashtable has1 = new Hashtable();
        has1.Add("1", "Welcome");
        has1.Add("2", "to");
        has1.Add("3", "geeks");
        has1.Add("4", "for");
        has1.Add("5", "geeks");
  
        // --------- Using IsSynchronized Property 
  
        // Creating a synchronized packing
        // around the Hashtable
        Hashtable has2 = Hashtable.Synchronized(has1);
  
        // print the status of both Hashtables
        Console.WriteLine("has1 Hashtable is {0}."
             has1.IsSynchronized ? "synchronized"
                               "not synchronized");
  
        Console.WriteLine("has2 Hashtable is {0}."
             has2.IsSynchronized ? "synchronized"
                               "not synchronized");
  
        // --------- Using Count Property
  
        Console.WriteLine("Total Number of Elements in has1: "
                                                + has1.Count);
    }
}

chevron_right


Output:

has1 Hashtable is not synchronized.
has2 Hashtable is synchronized.
Total Number of Elements in has1: 5

Methods

METHOD DESCRIPTION
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.
GetHash(Object) Returns the hash code for the specified key.
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.
KeyEquals(Object, Object) Compares a specific Object with a specific key in the Hashtable.
MemberwiseClone() Creates a shallow copy of the current Object.
OnDeserialization(Object) Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.
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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate Add()
// and Remove() Methods
using System;
using System.Collections;
  
class Program {
  
    // Main method
    static void Main(string[] args)
    {
  
        // -------- Add() Method --------
  
        // create and initalize Hash table
        // using Add() method
        Hashtable g = new Hashtable();
        g.Add("1", "Welcome");
        g.Add("2", "to");
        g.Add("3", "Geeks");
        g.Add("4", "for");
        g.Add("5", "Geeks");
  
        ICollection key = g.Keys;
  
        // Print Hash table
        Console.WriteLine("Hashtable Contains:");
  
        foreach(var val in key)
        {
            Console.WriteLine(val + "-" + g[val]);
        }
  
        Console.WriteLine();
  
        // --------- Remove() Method ----------'
  
        // Remove element 4
        // using Remove() method
        g.Remove("4");
  
        // printing updated Hash table
        Console.WriteLine("Hashtable after removing element 4:");
  
        foreach(var val in key)
        {
            Console.WriteLine(val + "-" + g[val]);
        }
    }
}

chevron_right


Output:

Hashtable Contains:
2-to
3-Geeks
5-Geeks
1-Welcome
4-for

Hashtable after removing element 4:
2-to
3-Geeks
5-Geeks
1-Welcome

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.