ContainsKey in C#

The ContainsKey method in C# is a Dictionary method that checks whether a specified key exists in the dictionary. It returns a boolean value − true if the key is found, false otherwise. This method is essential for safe dictionary operations to avoid exceptions when accessing non-existent keys.

Syntax

Following is the syntax for the ContainsKey method −

public bool ContainsKey(TKey key)

Parameters

  • key − The key to locate in the dictionary. This parameter cannot be null for reference types.

Return Value

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

Using ContainsKey for Safe Dictionary Access

The ContainsKey method prevents KeyNotFoundException when trying to access dictionary values −

using System;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        var dict = new Dictionary<string, int>() {
            {"TV", 1},
            {"Home Theatre", 2},
            {"Amazon Alexa", 3},
            {"Google Home", 5},
            {"Laptop", 5},
            {"Bluetooth Speaker", 6}
        };
        
        if (dict.ContainsKey("Laptop")) {
            Console.WriteLine("Laptop found with value: " + dict["Laptop"]);
        }
        
        if (dict.ContainsKey("Smartphone")) {
            Console.WriteLine("Smartphone found with value: " + dict["Smartphone"]);
        } else {
            Console.WriteLine("Smartphone not found in dictionary");
        }
    }
}

The output of the above code is −

Laptop found with value: 5
Smartphone not found in dictionary

Using ContainsKey with TryGetValue

For better performance when both checking existence and retrieving values, combine ContainsKey with TryGetValue

using System;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var products = new Dictionary<string, decimal>() {
            {"Mouse", 25.99m},
            {"Keyboard", 75.50m},
            {"Monitor", 299.99m}
        };
        
        // Using ContainsKey
        if (products.ContainsKey("Mouse")) {
            Console.WriteLine("Mouse price: $" + products["Mouse"]);
        }
        
        // Using TryGetValue (more efficient)
        if (products.TryGetValue("Keyboard", out decimal price)) {
            Console.WriteLine("Keyboard price: $" + price);
        }
        
        // Check non-existent key
        Console.WriteLine("Webcam exists: " + products.ContainsKey("Webcam"));
    }
}

The output of the above code is −

Mouse price: $25.99
Keyboard price: $75.50
Webcam exists: False

ContainsKey vs TryGetValue Performance

Method Use Case Performance
ContainsKey Only checking existence Single lookup operation
TryGetValue Check existence and get value More efficient − single lookup
ContainsKey + indexer Check then access value Less efficient − double lookup

Conclusion

The ContainsKey method is essential for safe dictionary operations in C#. It prevents exceptions when accessing dictionary values and should be used when you only need to check key existence. For scenarios where you need both existence checking and value retrieval, TryGetValue offers better performance.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements