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


The Hashtable class in C# represents a collection of key-value pairs. These key-value pairs are organized based on the hash code of the key that is calculated using the hash code function.

The key in the hashtable accesses the items. So given a key, we can access the corresponding value for that key in the hashtable. The keys in the hashtable are unique and non-null. The values however can be null or duplicated.

We have been discussing hashtable topics in our earlier tutorials. We continue the trend in this article as well. In this article, we will discuss how to check if a key exists in the hashtable collection.

So let’s begin.

How to Check if Key Exists in Hashtable?

There are two methods provided by the Hashtable class that help us to check if the key exists in the hashtable. These two methods are, ContainsKey() and Contains(). We will discuss these methods one by one.

Method Description
ContainsKey(object key) Returns true if the key exists or returns false.
Contains() Returns true if the key exists, false otherwise.

The ContainsKey() Method

The ContainsKey() method of the hashtable class takes a key object as a parameter and returns true if this key object is present in the hashtable. It returns false if the element with the specified key is not present in the hashtable.

Following is the general prototype of the ContainsKey() method.

Syntax

public virtual bool ContainsKey(object key);

Parameters

  • Key − The key of type System.object which is to be located in the Hashtable.

Return Type

  • True − if the Hashtable contains an element with the specified key.

  • False − Hashtable does not contain elements with the specified key.

Exception

  • ArgumentNullException − if the key is null.

Example

The following program demonstrates the use of the ContainsKey() method to check if the key exists in the hashtable.

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;
      Console.WriteLine("Enter the key which is to be found:");
      key = Console.ReadLine();
      if(key != ""){
         if (myHashTable.ContainsKey(key))
            Console.WriteLine("myHashTable contains the key={0}",key);
         else
            Console.WriteLine("myHashTable doesn't contain the key={0}",key);
      }
   }
}

In this program, we have a hashtable myHashTable with five elements in it. The program then prompts the user to enter the key that is to be found. When a user enters the key, the method ContainsKey() is executed with the entered key as a parameter. If the method returns true, the program displays an appropriate message. If the method returns false, it means the key is not present and an appropriate message is displayed.

The following output is generated when the user enters the key and the ContainsKey() method returns true.

Output

Enter the key which is to be found:
P
myHashTable contains the key=P

Since there is an element present in the hashtable with the given key (P), the ContainsKey() method returns true. The appropriate message is then displayed by the program.

Now let’s rerun the program and generate a second output as shown below.

Output

Enter the key whose value is to be found:
X
myHashTable doesn't contain the key=X

Here the message displayed says that the hashtable doesn’t contain the key. The key entered is X, which is not part of the hashtable. Hence ContainsKey() method returns false.

Contains() Method

The Contains() method is yet another method t check if the key is present in the hashtable. Like ContainsKey() method, the Contains() method also takes a key object as the parameter and searches the hashtable to check if the element with the specified key is present in the hashtable.

The prototype of the Contains() method is given below.

Syntax

public virtual bool Contains (object key);

Parameters

  • Key − the Key object to be located in the Hashtable.

Return Type

  • True − the Hashtable contains an element with the specified key.

  • False − the hashtable does not contain an element with the specified key.

Exception

This method throws ArgumentNullException if the key is null.

Example

The next program demonstrates the Contains() method in use.

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(key != ""){
         if (myHashTable.Contains(key))
            Console.WriteLine("myHashTable contains the key={0}",key);
         else
            Console.WriteLine("myHashTable doesn't contain the key={0}",key);
      }
   }
}

The program is similar to the previous one except for the method change. Here we specify the key = “F”. The contains() method with the key as a parameter is called and it returns the appropriate value once it traverses the hashtable. Depending on the value returned, the output of the program is shown.

The following output is generated by the program when key = F is entered by the user.

Output

myHashTable contains the key=F

The output says the hashtable contains the key since the element with the specified key is present in the hashtable and hence Contains() method has returned true.

In this article, we have discussed ContainsKey() and Contains() methods, which are used to check if the specified key is present in the hashtable collection. We have also seen programming examples to understand the concept. We will learn more concepts in subsequent tutorials.

Updated on: 14-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements