Dictionarydict = new Dictionary (); dict.Add("apple", 5); dict.Add("orange", 10); dict.Add("banana", 7); bool hasKey = dict.ContainsKey("apple"); Console.WriteLine(hasKey); // Output: true
SortedDictionaryIn both examples, we create a dictionary and sorted dictionary, respectively, using different key-value pairs. We then use the ContainsKey method to check if the key exists in the dictionary/sorted dictionary. The output will be 'true' if the key exists, or 'false' if it does not. The ContainsKey method is part of the System.Collections.Generic package library in C#.sortedDict = new SortedDictionary (); sortedDict.Add(3, "apple"); sortedDict.Add(5, "banana"); sortedDict.Add(1, "orange"); bool hasKey = sortedDict.ContainsKey(5); Console.WriteLine(hasKey); // Output: true