KeyNotFoundException in C#

The KeyNotFoundException in C# is thrown when you attempt to access a key that does not exist in a Dictionary collection. This exception occurs specifically when using the indexer syntax dictionary[key] to retrieve a value.

When KeyNotFoundException Occurs

This exception is thrown in the following scenarios −

  • Accessing a Dictionary using dict[key] where the key doesn't exist

  • Using the indexer on collections like SortedDictionary or SortedList with non-existent keys

  • Attempting to retrieve values from key-value collections without checking key existence

Dictionary Key Access Safe Access TryGetValue() ContainsKey() Returns false if key not found Risky Access dict[key] Throws exception if key not found Choose safe methods to avoid KeyNotFoundException

Example of KeyNotFoundException

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      try {
         var dict = new Dictionary<string, string>() {
            {"TV", "Electronics"},
            {"Laptop", "Computers"},
         };
         Console.WriteLine(dict["Pen Drive"]);
      }
      catch (KeyNotFoundException e) {
         Console.WriteLine("KeyNotFoundException: " + e.Message);
      }
   }
}

The output of the above code is −

KeyNotFoundException: The given key 'Pen Drive' was not present in the dictionary.

Using TryGetValue() Method

The safest way to access Dictionary values is using the TryGetValue() method, which returns false if the key doesn't exist −

using System;
using System.Collections.Generic;

public class SafeDemo {
   public static void Main() {
      var dict = new Dictionary<string, string>() {
         {"TV", "Electronics"},
         {"Laptop", "Computers"},
      };
      
      string value;
      if (dict.TryGetValue("Pen Drive", out value)) {
         Console.WriteLine("Found: " + value);
      } else {
         Console.WriteLine("Key 'Pen Drive' not found in dictionary");
      }
      
      if (dict.TryGetValue("TV", out value)) {
         Console.WriteLine("Found: " + value);
      }
   }
}

The output of the above code is −

Key 'Pen Drive' not found in dictionary
Found: Electronics

Using ContainsKey() Method

Another approach is to check if the key exists using ContainsKey() before accessing −

using System;
using System.Collections.Generic;

public class ContainsKeyDemo {
   public static void Main() {
      var dict = new Dictionary<string, string>() {
         {"TV", "Electronics"},
         {"Laptop", "Computers"},
      };
      
      string keyToFind = "Mobile";
      
      if (dict.ContainsKey(keyToFind)) {
         Console.WriteLine(keyToFind + ": " + dict[keyToFind]);
      } else {
         Console.WriteLine("Key '" + keyToFind + "' does not exist");
      }
      
      keyToFind = "TV";
      if (dict.ContainsKey(keyToFind)) {
         Console.WriteLine(keyToFind + ": " + dict[keyToFind]);
      }
   }
}

The output of the above code is −

Key 'Mobile' does not exist
TV: Electronics

Comparison of Methods

Method Behavior on Missing Key Performance
dict[key] Throws KeyNotFoundException Fastest (if key exists)
TryGetValue() Returns false, outputs default value Good performance, no exceptions
ContainsKey() + dict[key] Returns false from ContainsKey() Two dictionary lookups required

Conclusion

KeyNotFoundException occurs when accessing non-existent keys in Dictionary collections using the indexer syntax. To avoid this exception, use TryGetValue() or ContainsKey() methods to safely check for key existence before accessing values.

Updated on: 2026-03-17T07:04:35+05:30

649 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements