How to Delete Item from Hashtable Collection in C#?

The Hashtable in C# is a collection of key-value pairs that are organized based on the hash code of the key. Items in the hashtable are accessed using a key, and the Hashtable class provides various methods to perform operations like adding, removing, and checking for the existence of specified keys.

In this article, we will discuss how to delete an item from the hashtable collection using a specified key with the Remove() method.

Syntax

The Hashtable class provides the Remove() method to delete an item from the hashtable collection

public virtual void Remove(object key);

Parameters

  • key The key of the element to be removed from the hashtable collection. This is of type System.Object.

Return Value

The Remove() method does not return any value (void).

Exceptions

  • ArgumentNullException Thrown if the specified key is null.

  • NotSupportedException Thrown if the hashtable has a fixed size or is read-only.

The Remove() method does not throw any exception if the specified key is not present in the hashtable. The hashtable remains unchanged if the key is not found.

Using Remove() to Delete Items

Example 1 Basic Item Removal

using System;
using System.Collections;

class MyHashTable {
   public static void Main() {
      // Creating a Hashtable
      Hashtable numberNames = new Hashtable();

      // Adding elements in Hashtable
      numberNames.Add("2", "Two");
      numberNames.Add("13", "Thirteen");
      numberNames.Add("24", "Twenty Four");
      numberNames.Add("59", "Fifty Nine");

      // Print the contents of Hashtable
      Console.WriteLine("**********Contents of Hashtable**********");
      foreach(var item in numberNames.Keys) {
         Console.WriteLine("key = {0}, Value = {1}", item, numberNames[item]);
      }

      // Remove the element with key "13"
      string key = "13";
      numberNames.Remove(key);

      // Display the hashtable after deletion
      Console.WriteLine("<br>******Contents of Hashtable(after deletion)******");
      foreach(var item in numberNames.Keys) {
         Console.WriteLine("key = {0}, Value = {1}", item, numberNames[item]);
      }
   }
}

The output of the above code is

**********Contents of Hashtable**********
key = 59, Value = Fifty Nine
key = 24, Value = Twenty Four
key = 13, Value = Thirteen
key = 2, Value = Two

******Contents of Hashtable(after deletion)******
key = 59, Value = Fifty Nine
key = 24, Value = Twenty Four
key = 2, Value = Two

Example 2 Removing Non-Existent Key

using System;
using System.Collections;

public class HashTableExample {
   public static void Main() {
      // Create a new Hashtable
      var colors = new Hashtable();
      colors.Add("R", "Red");
      colors.Add("G", "Green");
      colors.Add("B", "Blue");

      // Display initial contents
      Console.WriteLine("Initial Hashtable:");
      foreach (DictionaryEntry item in colors) {
         Console.WriteLine("    {0}: {1}", item.Key, item.Value);
      }

      // Try to remove a key that doesn't exist
      string keyToRemove = "Y";
      Console.WriteLine("\nAttempting to remove key: " + keyToRemove);
      colors.Remove(keyToRemove);

      // Display contents after attempted removal
      Console.WriteLine("\nHashtable after removal attempt:");
      foreach (DictionaryEntry item in colors) {
         Console.WriteLine("    {0}: {1}", item.Key, item.Value);
      }
      
      Console.WriteLine("Count remains: " + colors.Count);
   }
}

The output of the above code is

Initial Hashtable:
    B: Blue
    R: Red
    G: Green

Attempting to remove key: Y

Hashtable after removal attempt:
    B: Blue
    R: Red
    G: Green
Count remains: 3

Using Remove() with Contains() Check

Example 3 Safe Removal with Key Verification

using System;
using System.Collections;

public class SafeRemoval {
   public static void Main() {
      // Create hashtable with student data
      Hashtable students = new Hashtable();
      students.Add(101, "Alice");
      students.Add(102, "Bob");
      students.Add(103, "Charlie");

      Console.WriteLine("Initial students:");
      foreach (DictionaryEntry student in students) {
         Console.WriteLine("ID: {0}, Name: {1}", student.Key, student.Value);
      }

      // Safe removal with check
      int studentId = 102;
      if (students.Contains(studentId)) {
         students.Remove(studentId);
         Console.WriteLine("\nStudent with ID {0} removed successfully.", studentId);
      } else {
         Console.WriteLine("\nStudent with ID {0} not found.", studentId);
      }

      // Check removal of non-existent key
      studentId = 999;
      if (students.Contains(studentId)) {
         students.Remove(studentId);
         Console.WriteLine("Student with ID {0} removed successfully.", studentId);
      } else {
         Console.WriteLine("Student with ID {0} not found.", studentId);
      }

      Console.WriteLine("\nFinal students:");
      foreach (DictionaryEntry student in students) {
         Console.WriteLine("ID: {0}, Name: {1}", student.Key, student.Value);
      }
   }
}

The output of the above code is

Initial students:
ID: 103, Name: Charlie
ID: 101, Name: Alice
ID: 102, Name: Bob

Student with ID 102 removed successfully.
Student with ID 999 not found.

Final students:
ID: 103, Name: Charlie
ID: 101, Name: Alice

Key Points about Remove() Method

  • The Remove() method deletes the key-value pair from the hashtable based on the specified key.

  • If the key does not exist, no exception is thrown and the hashtable remains unchanged.

  • The method reduces the Count property of the hashtable by one when an item is successfully removed.

  • It is safe to call Remove() without checking if the key exists first.

Conclusion

The Remove() method of the Hashtable class provides a simple way to delete items from a hashtable collection using a specified key. The method handles non-existent keys gracefully without throwing exceptions, making it safe to use in various scenarios.

Updated on: 2026-03-17T07:04:36+05:30

599 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements