0
0
CsharpHow-ToBeginner · 3 min read

How to Check if Key Exists in Dictionary in C#

In C#, you can check if a key exists in a Dictionary using the ContainsKey method. It returns true if the key is present and false otherwise.
📐

Syntax

The ContainsKey method checks if a specific key exists in the dictionary.

  • dictionary.ContainsKey(key): Returns true if key is found, otherwise false.
csharp
bool ContainsKey(TKey key);
💻

Example

This example shows how to create a dictionary, check if a key exists, and print a message based on the result.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var ages = new Dictionary<string, int>
        {
            {"Alice", 30},
            {"Bob", 25}
        };

        string keyToCheck = "Alice";

        if (ages.ContainsKey(keyToCheck))
        {
            Console.WriteLine($"Key '{keyToCheck}' found with value: {ages[keyToCheck]}");
        }
        else
        {
            Console.WriteLine($"Key '{keyToCheck}' not found.");
        }
    }
}
Output
Key 'Alice' found with value: 30
⚠️

Common Pitfalls

One common mistake is trying to access a dictionary value directly without checking if the key exists, which causes an exception if the key is missing.

Always use ContainsKey before accessing the value or use TryGetValue for safer access.

csharp
var dict = new Dictionary<string, int>();
dict["one"] = 1;

// Wrong: Throws KeyNotFoundException if key missing
// int value = dict["two"];

// Right: Check first
if (dict.ContainsKey("two"))
{
    int value = dict["two"];
}

// Or use TryGetValue
if (dict.TryGetValue("two", out int val))
{
    Console.WriteLine(val);
}
else
{
    Console.WriteLine("Key not found.");
}
📊

Quick Reference

MethodDescription
ContainsKey(key)Returns true if the key exists in the dictionary.
TryGetValue(key, out value)Tries to get the value for the key safely without exceptions.
dictionary[key]Accesses the value directly; throws exception if key missing.

Key Takeaways

Use ContainsKey to check if a key exists before accessing its value.
Accessing a dictionary value directly without checking can cause exceptions.
TryGetValue is a safe alternative to check and get a value in one step.
ContainsKey returns a boolean indicating presence of the key.
Always handle the case when the key is not found to avoid runtime errors.