C# KeyNotFoundException Fix

by Sam Allen - Updated January 7, 2010

You are encountering the KeyNotFoundException in your program written in the C# programming language. This is likely caused by your usage of the Dictionary collection, and you want a quick way to fix the problem. Here we examine the KeyNotFoundException, first seeing the code that is causing the exception and then fixing the code while not hurting performance or clarity.

Catching KeyNotFoundException

First, here we see some code that looks correct, but actually has a severe flaw. The problem is that you cannot look up a key that doesn't exist in the Dictionary and try to assign your variable to its value. The KeyNotFoundException here is thrown on the line where "string value = test["two"]". That string doesn't exist in the collection.

=== Program that throws KeyNotFoundException (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        try
        {
            //
            // Create new Dictionary with string key of "one"
            //
            Dictionary<string, string> test = new Dictionary<string, string>();
            test.Add("one", "value");

            //
            // Try to access key of "two"
            //
            string value = test["two"];
        }
        catch (Exception ex)
        {
            //
            // An exception will be thrown.
            //
            Console.WriteLine(ex);
        }
    }
}

=== Output of the program ===

System.Collections.Generic.KeyNotFoundException:
    The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()
...

Fixing key lookup

Here we look at how you can fix this exception by using the TryGetValue method on the Dictionary constructed type. Note that could use ContainsKey instead of TryGetValue, but the below code preserves the intention of the previous code.

=== Program that doesn't throw (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, string> 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");
        }
    }
}

=== Output of the program (C#) ===

Not found

Note on preceding example. You always have to use the if statement when testing values in the Dictionary, because there is always a possibility that the key won't exist. Also, the C# compiler cannot detect missing keys; they can only be detected at runtime.

Summary

Here we saw how you can raise and catch the KeyNotFoundException during runtime, and then we saw how you can avoid causing the exception. We discussed alternatives, such as TryGetValue and ContainsKey, and looked at a program that does not have this problem.

(See Dictionary Examples, Keys and Values.)

(Do not copy this page.)

Dot Net Perls | Search
Exceptions | Collection Was Modified Exception | Exception Overview | File.Delete Exceptions | FileNotFoundException Tips | NullReferenceException and Null Parameter
C# | SaveFileDialog Tutorial | IntegralHeight Property (Windows Forms) | Array.FindIndex Method | File.Replace Method
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen