Check whether a Hashtable contains a specific key or not in C#


To check whether a Hashtable contains a specific key or not, the code is as follows −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Hashtable hash = new Hashtable();
      hash.Add("One", "Katie");
      hash.Add("Two", "John");
      hash.Add("Three", "Barry");
      hash.Add("Four", "");
      hash.Add("Five","Harry");
      hash.Add("Six", "F");
      hash.Add("Seven", "Tom");
      hash.Add("Eight","Andy");
      hash.Add("Nine", "I");
      hash.Add("Ten", "Tim");
      Console.WriteLine("Hashtable Key and Value pairs...");
      foreach(DictionaryEntry entry in hash){
         Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
      }
      Console.WriteLine("Is the Hashtable having fixed size? = "+hash.IsFixedSize);
      Console.WriteLine("If Hashtable read-only? = "+hash.IsReadOnly);
      Hashtable hash2 = Hashtable.Synchronized(hash);
      Console.WriteLine("Is Hash synchronized = "+hash2.IsSynchronized);
      Console.WriteLine("Does Hashtable contains the key Ten = "+hash.Contains("Ten"));
   }
}

Output

This will produce the following output −

Hashtable Key and Value pairs...
One and Katie
Ten and Tim
Five and Harry
Three and Barry
Seven and Tom
Two and John
Four and
Eight and Andy
Nine and I
Six and F
Is the Hashtable having fixed size? = False
If Hashtable read-only? = False
Is Hash synchronized = True
Does Hashtable contains the key Ten = True

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Hashtable hash = new Hashtable();
      hash.Add("1", "AB");
      hash.Add("2", "BC");
      hash.Add("3", "DE");
      hash.Add("4", "EF");
      hash.Add("5", "GH");
      hash.Add("6", "IJ");
      hash.Add("7", "KL");
      hash.Add("8", "MN");
      hash.Add("9", "OP");
      hash.Add("10", "QR");
      Console.WriteLine("Value at key 3 = "+hash["3"]);
      Console.WriteLine("Does Hashtable contains the key 12 = "+hash.Contains("12"));
   }
}

Output

This will produce the following output −

Value at key 3 = DE
Does Hashtable contains the key 12 = False

Updated on: 11-Dec-2019

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements