ContainsKey is a method in C# that checks whether a dictionary contains a specified key or not. If the key is present in the dictionary, ContainsKey returns true, otherwise returns false. This method is useful when we want to check for the existence of a key in the dictionary before performing any operation on it.
Example 1: Checking if a key exists in a dictionary
if (dictionary.ContainsKey("apple")) { Console.WriteLine("The dictionary contains the key 'apple'"); } else { Console.WriteLine("The dictionary does not contain the key 'apple'"); }
// Output: The dictionary contains the key 'apple'
In this example, we have created a dictionary of string and integer values. We are then using the ContainsKey method to check whether the dictionary contains the key "apple" or not.
Example 2: Using ContainsKey to retrieve the value of a key
if (dictionary.ContainsKey("banana")) { int value = dictionary["banana"]; Console.WriteLine("The value of 'banana' is: " + value); }
// Output: The value of 'banana' is: 2
In this example, we are using ContainsKey to check if the dictionary has the key "banana". If it exists, we are retrieving its corresponding value using the index operator.
Package/Library: ContainsKey method is part of the System.Collections.Generic package in C#.
C# (CSharp) this.ContainsKey - 30 examples found. These are the top rated real world C# (CSharp) examples of this.ContainsKey extracted from open source projects. You can rate examples to help us improve the quality of examples.