Dictionary.ContainsKey() Method in C#

The Dictionary.ContainsKey() method in C# checks whether the Dictionary<TKey, TValue> contains the specified key. This method returns true if the key exists, otherwise false.

Syntax

public bool ContainsKey(TKey key);

Parameters

key − The key to locate in the dictionary. Cannot be null for reference types.

Return Value

Returns true if the dictionary contains an element with the specified key; otherwise, false.

Using ContainsKey() to Check for Existing Keys

This example demonstrates checking for a key that exists in the dictionary −

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      Dictionary<string, string> dict = new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      dict.Add("Four", "Kevin");
      dict.Add("Five", "Nathan");
      
      Console.WriteLine("Count of elements = " + dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict) {
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      
      if (dict.ContainsKey("Three"))
         Console.WriteLine("Key 'Three' found!");
      else
         Console.WriteLine("Key 'Three' isn't in the dictionary!");
   }
}

The output of the above code is −

Count of elements = 5

Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Key 'Three' found!

Using ContainsKey() for Non-Existing Keys

This example shows what happens when checking for a key that doesn't exist −

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      Dictionary<string, string> dict = new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      
      Console.WriteLine("Checking for existing key 'Two':");
      if (dict.ContainsKey("Two"))
         Console.WriteLine("Key 'Two' found!");
      else
         Console.WriteLine("Key 'Two' not found!");
         
      Console.WriteLine("\nChecking for non-existing key 'Seven':");
      if (dict.ContainsKey("Seven"))
         Console.WriteLine("Key 'Seven' found!");
      else
         Console.WriteLine("Key 'Seven' not found!");
   }
}

The output of the above code is −

Checking for existing key 'Two':
Key 'Two' found!

Checking for non-existing key 'Seven':
Key 'Seven' not found!

Using ContainsKey() for Safe Dictionary Access

ContainsKey() is commonly used to avoid exceptions when accessing dictionary values −

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      Dictionary<int, string> products = new Dictionary<int, string>();
      products.Add(101, "Laptop");
      products.Add(102, "Mouse");
      products.Add(103, "Keyboard");
      
      int[] searchIds = {101, 104, 102};
      
      foreach(int id in searchIds) {
         if (products.ContainsKey(id)) {
            Console.WriteLine("Product ID {0}: {1}", id, products[id]);
         } else {
            Console.WriteLine("Product ID {0}: Not found", id);
         }
      }
   }
}

The output of the above code is −

Product ID 101: Laptop
Product ID 104: Not found
Product ID 102: Mouse

Common Use Cases

  • Avoiding KeyNotFoundException − Check if a key exists before accessing its value.

  • Conditional Operations − Perform operations only when specific keys are present.

  • Data Validation − Verify required keys exist before processing.

  • Safe Updates − Update existing entries without adding duplicates.

Conclusion

The Dictionary.ContainsKey() method is essential for safe dictionary operations in C#. It helps prevent runtime exceptions by allowing you to verify key existence before accessing or manipulating dictionary values, making your code more robust and reliable.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements