Skip to content
Related Articles

Related Articles

Improve Article

C# | Check if the StringDictionary contains a specific key

  • Last Updated : 01 Feb, 2019

StringDictionary.ContainsKey(String) method is used to check whether the StringDictionary contains a specific key or not.

Syntax:

public virtual bool ContainsKey (string key);

Here, key is the key to locate in the StringDictionary.

Return Value: This method returns true if the StringDictionary contains an entry with the specified key, otherwise it returns the false.

Exception: This method will give ArgumentNullException if the key is null.



Below programs illustrate the use of StringDictionary.ContainsKey(String) method:

Example 1:




// C# code to check if the
// StringDictionary contains
// a specific key
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a StringDictionary named myDict
        StringDictionary myDict = new StringDictionary();
  
        // Adding key and value into the StringDictionary
        myDict.Add("G", "Geeks");
        myDict.Add("F", "For");
        myDict.Add("C", "C++");
        myDict.Add("DS", "Data Structures");
        myDict.Add("N", "Noida");
  
        // Checking if "DS" is contained in
        // StringDictionary myDict
        if (myDict.ContainsKey("DS"))
            Console.WriteLine("StringDictionary myDict contains the key");
        else
            Console.WriteLine("StringDictionary myDict does not contain the key");
    }
}

Output:

StringDictionary myDict contains the key

Example 2:




// C# code to check if the
// StringDictionary contains
// a specific key
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a StringDictionary named myDict
        StringDictionary myDict = new StringDictionary();
  
        // Adding key and value into the StringDictionary
        myDict.Add("G", "Geeks");
        myDict.Add("F", "For");
        myDict.Add("C", "C++");
        myDict.Add("DS", "Data Structures");
        myDict.Add("N", "Noida");
  
        // Checking if "null" is contained in
        // StringDictionary myDict
        // This should raise "ArgumentNullException"
        // as the key is null
        if (myDict.ContainsKey(null))
            Console.WriteLine("StringDictionary myDict contains the key");
        else
            Console.WriteLine("StringDictionary myDict does not contain the key");
    }
}

Runtime Error:

Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: key

Note:

  • The key is handled in a case-insensitive manner i.e, it is translated to lowercase before it is added to the string dictionary.
  • This method is an O(1) operation.

Reference:




My Personal Notes arrow_drop_up
Recommended Articles
Page :