Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
ContainsKey Method
Collapse the table of content
Expand the table of content

IDictionary.ContainsKey Method

Determines whether the IDictionary contains an element with the specified key.

Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)

bool ContainsKey (
	TKey key
boolean ContainsKey (
	TKey key
function ContainsKey (
	key : TKey
) : boolean
Not applicable.



The key to locate in the IDictionary.

Return Value

true if the IDictionary contains an element with the key; otherwise, false.

Exception typeCondition


key is a null reference (Nothing in Visual Basic).

Implementations can vary in how they determine equality of objects; for example, the List class uses Comparer.Default, whereas the Dictionary class allows the user to specify the IComparer implementation to use for comparing keys.

Implementations can vary in whether they allow key to be a null reference (Nothing in Visual Basic).

The following code example shows how to use the ContainsKey method to test whether a key exists prior to calling the Add method. It also shows how to use the TryGetValue method, which can be a more efficient way to retrieve values if a program frequently tries key values that are not in the dictionary. Finally, it shows how to insert items using Item property (the indexer in C#).

This code is part of a larger example that can be compiled and executed. See System.Collections.Generic.IDictionary.

    // ContainsKey can be used to test keys before inserting 
    // them.
    if (!openWith.ContainsKey("ht"))
        openWith.Add("ht", "hypertrm.exe");
        Console.WriteLine("Value added for key = \"ht\": {0}", 


    // When a program often has to try keys that turn out not to
    // be in the dictionary, TryGetValue can be a more efficient 
    // way to retrieve values.
    string value = "";
    if (openWith.TryGetValue("tif", out value))
        Console.WriteLine("For key = \"tif\", value = {0}.", value);
        Console.WriteLine("Key = \"tif\" is not found.");


    // The indexer throws an exception if the requested key is
    // not in the dictionary.
        Console.WriteLine("For key = \"tif\", value = {0}.", 
    catch (KeyNotFoundException)
        Console.WriteLine("Key = \"tif\" is not found.");

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

.NET Compact Framework

Supported in: 2.0

XNA Framework

Supported in: 1.0

Community Additions

© 2015 Microsoft