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:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary myDict = new StringDictionary();
myDict.Add( "G" , "Geeks" );
myDict.Add( "F" , "For" );
myDict.Add( "C" , "C++" );
myDict.Add( "DS" , "Data Structures" );
myDict.Add( "N" , "Noida" );
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:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary myDict = new StringDictionary();
myDict.Add( "G" , "Geeks" );
myDict.Add( "F" , "For" );
myDict.Add( "C" , "C++" );
myDict.Add( "DS" , "Data Structures" );
myDict.Add( "N" , "Noida" );
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:
Share your thoughts in the comments
Please Login to comment...