I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the
Use Dictionary.TryGetValue instead:
Dictionary dictionary = new Dictionary(); int key = 0; dictionary[key] = "Yes"; string value; if (dictionary.TryGetValue(key, out value)) { Console.WriteLine("Fetched value: {0}", value); } else { Console.WriteLine("No such key: {0}", key); }