What happens when you read a missing key with the indexer of a Dictionary in C#?
Correct answer D. A KeyNotFoundException is thrown
Explanation
The Dictionary indexer throws KeyNotFoundException when the key does not exist. It does not return a default value as some languages' maps do. To read safely, use TryGetValue(key, out var value), which returns false for a missing key, or ContainsKey first. Assigning through the indexer, by contrast, adds or overwrites the entry.
Answer checked How we write and check questions
Discussion