KeyNotFoundException: Key Not Present in DictionaryUnderstand KeyNotFoundException and why it is encountered when using a Dictionary.
This page was last reviewed on Nov 30, 2023.
KeyNotFoundException. In a C# program, a KeyNotFoundException can be thrown. This is likely caused by a lookup done on a key (one that is not present) in a Dictionary collection.
A solution. As always we want a quick way to fix the problem. We can use an if-statement with TryGetValue to avoid this exception.
Dictionary ContainsKey
Dictionary TryGetValue
Example. Here we see some code that looks correct. But it has a severe flaw. You cannot look up a key that is not found in the Dictionary and try to assign your variable to its value.
Here The KeyNotFoundException is thrown on the final line of the try-block. The string "test" is not present in the collection.
using System; using System.Collections.Generic; class Program { static void Main() { try { // Part 1: create new Dictionary with string key "one". var test = new Dictionary<string, string>(); test.Add("one", "value"); // Part 2: try to access key "two". string value = test["two"]; } catch (Exception ex) { // Part 3: an exception will be thrown. Console.WriteLine(ex); } } }
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.ThrowHelper.ThrowKeyNotFoundException() ...
Example 2. We can fix this exception by using the TryGetValue method. Note that could use ContainsKey instead of TryGetValue. But we preserve the intention of the previous code here.
Important We use if-statement when testing values in the Dictionary, because there is always a possibility that the key will not exist.
Info The C# compiler cannot detect missing keys. They can only be detected at runtime.
using System; using System.Collections.Generic; class Program { static void Main() { var test = new Dictionary<string, string>(); test.Add("one", "value"); // Use TryGetValue to avoid KeyNotFoundException. string value; if (test.TryGetValue("two", out value)) { Console.WriteLine("Found"); } else { Console.WriteLine("Not found"); } } }
Not found
It is possible to raise and catch the KeyNotFoundException during execution. But it is best to avoid causing the exception—we tested a program that does not have this problem.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 30, 2023 (edit).
© 2007-2024 Sam Allen.