Quick Answer
Handle missing dictionary keys.
Understanding the Issue
Occurs when trying to access a non-existent key in a dictionary collection.
The Problem
This code demonstrates the issue:
Csharp
Error
var dict = new Dictionary<string, int>();
var value = dict["missing"]; // Throws
The Solution
Here's the corrected code:
Csharp
Fixed
// Solution 1: Check key existence
if (dict.ContainsKey("key")) {
value = dict["key"];
}
// Solution 2: TryGetValue
if (dict.TryGetValue("key", out var val)) {
// Use val
}
// Solution 3: Dictionary extensions
public static TValue GetValueOrDefault<TKey, TValue>(
this Dictionary<TKey, TValue> dict,
TKey key,
TValue defaultValue = default) {
return dict.TryGetValue(key, out var value) ? value : defaultValue;
}
// Solution 4: ConcurrentDictionary
var concurrentDict = new ConcurrentDictionary<string, int>();
value = concurrentDict.GetOrAdd("key", k => 0);
// Solution 5: Default value pattern
value = dict.ContainsKey("key") ? dict["key"] : 0;
Key Takeaways
Always check for key existence or use TryGetValue for safe dictionary access.