Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 existUsing the indexer on collections like
SortedDictionaryorSortedListwith non-existent keysAttempting to retrieve values from key-value collections without checking key existence
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.
