Export (0) Print
Expand All
1 out of 2 rated this helpful - Rate this topic

Dictionary.ContainsKey Method

Determines whether the Dictionary contains the specified key.

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

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

Parameters

key

The key to locate in the Dictionary.

Return Value

true if the Dictionary contains an element with the specified key; otherwise, false.
Exception typeCondition

ArgumentNullException

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

This method approaches an O(1) operation.

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 to retrieve values, which is an efficient way to retrieve values when a program frequently tries keys that are not in the dictionary. Finally, it shows the least efficient way to test whether keys exist, by using the Item property (the indexer in C#).

This code example is part of a larger example provided for the Dictionary class.

    // 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}", 
            openWith["ht"]);
    }

...

    // 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);
    }
    else
    {
        Console.WriteLine("Key = \"tif\" is not found.");
    }

...

    // The indexer throws an exception if the requested key is
    // not in the dictionary.
    try
    {
        Console.WriteLine("For key = \"tif\", value = {0}.", 
            openWith["tif"]);
    }
    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
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.