c# - How to check whether Dictionary contains a specific key

Dictionary ContainsKey() Method
.Net framework Dictionary<TKey, TValue>.ContainsKey() method allow us to determine whether the Dictionary<TKey, TValue> contains the specific key. the ContainsKey() method exists under System.Collections.Generic namespace.

this method require to pass a parameter named 'key'. this 'key' parameter value type is 'TKey' which represents the key to locate in the Dictionary<TKey, TValue>.

ContainsKey() method return value data type is System.Boolean. method return 'true', if the Dictionary<TKey, TValue> contains an element with the specified key. otherwise, the method return false.

this method implements as IDictionary<TKey, TValue>.ContainsKey(TKey) and IReadOnlyDictionary<TKey, TValue>.ContainsKey(TKey). the ContainsKey() method throw ArgumentNullException exception if the 'key' is null.

the following asp.net c# example code demonstrate us how can we determine whether the dictionary contains an element with the specified key programmatically at run time in an asp.net application.

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
        Dictionary<string, string> colors = new Dictionary<string, string>();
        colors.Add("Gold", "#FFD700");
        colors.Add("Gainsboro", "#DCDCDC");
        colors.Add("GhostWhite", "#F8F8FF");
        colors.Add("DodgerBlue", "#1E90FF");

        Label1.Text = "Dictionary Keys...<br />";

        foreach (string color in colors.Keys)
            Label1.Text += color + "<br />";

        //ContainsKey() method check Dictionary contains the specified key.
        Label1.Text += "<br />'DodgerBlue' Key Exists In Dictionary? " + colors.ContainsKey("DodgerBlue");
        Label1.Text += "<br />'Green' Key Exists In Dictionary? " + colors.ContainsKey("Green");

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Dictionary ContainsKey() Method - How to check Dictionary contains the specified key</title>
    <form id="form1" runat="server">
        <h2 style="color:Navy; font-style:italic;">
            System.Collections.Generic.Dictionary ContainsKey() Method
            <br /> How to check Dictionary contains the specified key
        <hr width="550" align="left" color="Navy" />
        <br />
             Font-Names="Courier New"
        <br /><br />
            Text="Test Dictionary ContainsKey() Method"
More c# examples