DictionarymyDictionary = new Dictionary (); myDictionary.Add("apple", 1); myDictionary.Add("banana", 2); myDictionary.Add("cherry", 3); if (myDictionary.ContainsKey("banana")) { Console.WriteLine("The dictionary contains the key 'banana'."); } else { Console.WriteLine("The dictionary does not contain the key 'banana'."); } Output: The dictionary contains the key 'banana'.
DictionaryIn both examples, the code checks if the dictionary contains a specific key using ContainsKey method. Depending on the result, an appropriate message is printed to the console. In Example 1, a string key is used while in Example 2, an integer key is used. The generic Dictionary class is used in both examples, which is a part of System.Collections.Generic package library.myDictionary = new Dictionary (); myDictionary.Add(1, "John"); myDictionary.Add(2, "Bob"); myDictionary.Add(3, "Alice"); int key = 2; if (myDictionary.ContainsKey(key)) { Console.WriteLine($"The dictionary contains the key {key} with value {myDictionary[key]}"); } else { Console.WriteLine($"The dictionary does not contain the key {key}"); } Output: The dictionary contains the key 2 with value Bob