
You want to test your Dictionary to see if it contains data accessible at a certain key. The Dictionary generic collection in the C# language and .NET Framework has a ContainsKey method that provides this functionality, but its usage can be tricky for developers unfamiliar with the syntax.
First, you will find the ContainsKey method on the Dictionary instance in your program by typing the variable name and pressing period, and then scrolling to ContainsKey. This method receives one parameter that is the same exact type as the key type in your Dictionary.
ContainsKey returns a Boolean value that indicates whether the key was found in the Dictionary or not. It will not throw if there were no keys matching. This example uses the ContainsKey method on a key that does exist and one that does not exist.
This C# example program uses the ContainsKey method on the Dictionary type.
Program that uses ContainsKey [C#]
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create Dictionary with two key value pairs.
var dictionary = new Dictionary<string, int>()
{
{"mac", 1000},
{"windows", 500}
};
// Use ContainsKey method.
if (dictionary.ContainsKey("mac") == true)
{
Console.WriteLine(dictionary["mac"]); // <-- Is executed
}
// Use ContainsKey method on another string.
if (dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false); // <-- Not hit
}
}
}
Output
1000 Evaluation result for dictionary["mac"]
Overview. The program defines the Main entry point and then populates the Dictionary with two key/value pairs, with string keys and integer values. The object creation expression at the start of Main is actually compiled into two Add method invocations. Next, the ContainsKey method is invoked twice. You can test ContainsKey in an if statement by comparing it to 'true' or 'false'.

The .NET Framework's base class library implements the ContainsKey method on the Dictionary type. The Dictionary has a private FindEntry method which loops over the entries in the Dictionary that are pointed to by the buckets array. When it finds a matching hash code, it compares the key values and then returns the actual value. The ContainsKey method discards some of the values it finds and simply returns a Boolean. For this reason, using TryGetValue can be used to perform these operations at one time, improving runtime speed.
TryGetValue Method
We looked at the ContainsKey method on the Dictionary constructed type in the C# programming language. This collection implements a lightning-fast lookup table, but will throw exceptions if you try to access an entry without using ContainsKey or TryGetValue initially. The example here showed how you can use ContainsKey before accessing the entry desired, resulting in correct execution of the program.
Collections