Practice mode C#

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.