How to Check if a Key Exists in the Hashtable in C#?

The Hashtable class in C# represents a collection of key-value pairs organized based on the hash code of each key. In hashtables, keys are unique and non-null, while values can be null or duplicated. Often, you need to verify whether a specific key exists before performing operations like retrieval or updates.

C# provides two methods to check if a key exists in a hashtable: ContainsKey() and Contains(). Both methods serve the same purpose but have slightly different naming conventions for clarity.

Syntax

Following is the syntax for the ContainsKey() method

public virtual bool ContainsKey(object key);

Following is the syntax for the Contains() method

public virtual bool Contains(object key);

Parameters

  • key The key object to be located in the Hashtable.

Return Value

  • true if the Hashtable contains an element with the specified key.

  • false if the Hashtable does not contain an element with the specified key.

Exception: Both methods throw ArgumentNullException if the key is null.

Method Comparison

Method Description Usage
ContainsKey(object key) Returns true if the key exists in the hashtable More explicit and self-documenting
Contains(object key) Returns true if the key exists in the hashtable Shorter method name, same functionality

Using ContainsKey() Method

Example

using System;
using System.Collections;

class Program {
   public static void Main() {
      // Create a Hashtable
      Hashtable myHashTable = new Hashtable();

      // Add elements in Hashtable
      myHashTable.Add("P", "Program");
      myHashTable.Add("T", "To");
      myHashTable.Add("F", "Find");
      myHashTable.Add("K", "Key");

      // Check if key exists
      string searchKey = "P";
      
      if (myHashTable.ContainsKey(searchKey)) {
         Console.WriteLine("myHashTable contains the key = " + searchKey);
         Console.WriteLine("Value: " + myHashTable[searchKey]);
      } else {
         Console.WriteLine("myHashTable doesn't contain the key = " + searchKey);
      }

      // Check for non-existing key
      string missingKey = "X";
      if (myHashTable.ContainsKey(missingKey)) {
         Console.WriteLine("Found key: " + missingKey);
      } else {
         Console.WriteLine("Key not found: " + missingKey);
      }
   }
}

The output of the above code is

myHashTable contains the key = P
Value: Program
Key not found: X

Using Contains() Method

Example

using System;
using System.Collections;

class Program {
   public static void Main() {
      // Create a Hashtable
      Hashtable myHashTable = new Hashtable();

      // Add elements in Hashtable
      myHashTable.Add("P", "Program");
      myHashTable.Add("T", "To");
      myHashTable.Add("F", "Find");
      myHashTable.Add("K", "Key");

      string key = "F";
      
      if (myHashTable.Contains(key)) {
         Console.WriteLine("myHashTable contains the key = " + key);
         Console.WriteLine("Associated value: " + myHashTable[key]);
      } else {
         Console.WriteLine("myHashTable doesn't contain the key = " + key);
      }
   }
}

The output of the above code is

myHashTable contains the key = F
Associated value: Find

Practical Example with Multiple Key Checks

Example

using System;
using System.Collections;

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

      // Array of student IDs to check
      int[] idsToCheck = {101, 104, 102, 105};

      Console.WriteLine("Checking student IDs:");
      foreach (int id in idsToCheck) {
         if (students.ContainsKey(id)) {
            Console.WriteLine("Student ID " + id + " exists: " + students[id]);
         } else {
            Console.WriteLine("Student ID " + id + " not found");
         }
      }
   }
}

The output of the above code is

Checking student IDs:
Student ID 101 exists: Alice
Student ID 104 not found
Student ID 102 exists: Bob
Student ID 105 not found

Common Use Cases

  • Safe value retrieval Check if key exists before accessing its value to avoid exceptions.

  • Conditional updates Update existing values or add new key-value pairs based on key existence.

  • Data validation Verify required keys are present in configuration or data structures.

  • Cache management Check if data is cached before performing expensive operations.

Conclusion

Both ContainsKey() and Contains() methods provide identical functionality for checking key existence in hashtables. Use these methods to safely verify key presence before accessing values, preventing potential runtime exceptions and ensuring robust code execution.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements