Hashtable In C#

Hashtable

In this article, We will learn about the concept of Hashtable in C#.

  • Hashtable is the non-generic collection that stores data in key-value pair, same as generic Dictionary collection.
  • In the Hashtable data, key-value pairs are organized based on the key’s hash code.
  • A key is used to access value from the Hashtable.
  • Basically, a Hashtable comes into the picture when we need to access an element by the key. 
  • Each element in the Hashtable has a key-value pair.

Hashtable Characteristics

  • Hashtable stores elements in the form of key-value pairs.
  • Hashtable comes under the System.Collection namespace.
  • Hashtable implements the IDictionary interface. 
  • Hashtable key must be unique and cannot be null or empty.
  • A value in a Hashtable can be null or empty or duplicate.
  • A value in the Hashtable can be accessed by passing the associated key in the indexer.
  • An element in the Hashtable is stored as DictionaryEntry objects.

There are a number of methods and properties available in Hashtable. So First, we will see the Method of Hashtable below,

  1. public virtual void Add(object key, object value)

 This method is used to add an element with the specified key-value pairs.

2. public virtual void Remove(object key):

 This method is used to remove an element with the specified key from the Hashtable.

3. public virtual void Clear():

This method is used when we want to remove all elements from the Hashtable.

4. public virtual bool ContainsKey(object key)

 This method is used to determine whether Hashtable contains a specified key or not.

5. public virtual bool ContainsValue(object value):

This method is used to determine whether Hashtable contains a specified value or not.

Now, we will see the Properties of Hashtable as below,

  1. Count:

Get the total number of elements available in Hashtable.

2. Keys:

Gets an ICollection containing the key in the Hashtable.

3. Values:

Gets an ICollection containing the value in the Hashtable.

4. Item:

Gets or sets the value associated with the specified key.

5. IsFixedSize:

This property will get a value indicating whether the Hashtable has a fixed size.

6. IsReadOnly:

This Property will get a value indicating whether the Hashtable is read-only.

Example of  Create Hashtable and Add element.

using System;
using System.Collections;

namespace HashtableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\n Hashtable Example");

            //Create Hashtable object
            Hashtable Phones = new Hashtable();

            //Add() method of Hashtable
            Phones.Add("Apple", "Iphone 11, Iphone 11 pro, Iphone 12, Iphone 12 mini");
            Phones.Add("Samsung", "Note 9, Note 10, Galaxy s20, Galaxy s20 ultra");
            Phones.Add("Realme", "Realme 6, Realme 6 pro, Realme 7, Realme 7i, Realme GT neo2");

            //Phones.Add("Realme","Realme 1"); it will allow only unique key, so it will give a compile time error

            Phones.Add("Vivo", ""); //Hashtable allow a null or empty or duplicate value

            //Display all Hashtable elements
            Console.WriteLine("\n Display Hastable element after Adding \n");
            foreach(DictionaryEntry Phone in Phones)
            {
                Console.WriteLine(" Key : {0}  ,  Value : {1}",Phone.Key,Phone.Value);
            }
        }
    }
}

The output of an above Example is as below,

In the above example, We can see that we are trying to add a duplicate key to Hashtable. But, As we know that the Hashtable will not allow adding a duplicate or null key, It allows only a unique key. But, we can add the null or empty, or duplicate value of an element in Hashtable.

Although, if we are trying to add a duplicate or null key. Then, it will give a compile-time error as below,

Example of Remove element from Hashtable,

//Remove Method of Hashtable
  if (Phones.ContainsKey("Vivo")) //It will chek whether it will contain an element of specified key.
  {
     Phones.Remove("Vivo"); //It will remove an element that contain a specified key "Vivo"
  }
  
//Display all Hashtable elements after Remove an element

  Console.WriteLine("\n Display Hastable element after Remove \n");
  foreach (DictionaryEntry Phone in Phones)
  {
    Console.WriteLine(" Key : {0}  ,  Value : {1}", Phone.Key, Phone.Value);
  }

The Output of the above example,

In the above example, we use the ContainsKey() method for checking the availability of a specified key in the Hashtable.

Example of how to update the element value,

//Update the value of specified key
  Phones["Apple"] = "Iphone 13 pro max";

 //Display all Hashtable elements after updating an element
 Console.WriteLine("\n Display Hastable element after Update \n");
 foreach (DictionaryEntry Phone in Phones)
 {
    Console.WriteLine(" Key : {0}  ,  Value : {1}", Phone.Key, Phone.Value);
 }

The output of the above example is as below,

Advantages 

  • The main advantage of Hashtable is synchronization.
  • It allows the execution time of lookup, retrieve, and set operations to remain nearly constant, even for a large number of sets.
  • Hashtable has the ability to locate the element quickly even when the amount of data is huge.
  • There is no requirement to scan through the entire data set to find an element or to sort the elements in order to perform a Binary search.
  • The key can be hashed and the value’s location can be found directly if the key for the desired element value is known.

Disadvantages

  • Hashtable collisions are practically unavoidable. when hashing a random subset of a large set of possible keys.
  • Hashtable becomes quite inefficient when there are many collisions occur.

I hope this article will help you to understand the concept of HAshtable in C#.

Thank you.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories