Bird
Raised Fist0

Find the error in this code:

medium📝 Debug Q7 of Q15
C Sharp (C#) - Collections
Find the error in this code:
var dict = new Dictionary<string, int>();
int value = dict["missingKey"];
ACompilation error due to missing key
BCode runs without error and value is null
Cvalue will be 0 by default
DKeyNotFoundException at runtime
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary indexer behavior

    Accessing a missing key with indexer throws KeyNotFoundException at runtime.
  2. Step 2: Analyze code snippet

    dict["missingKey"] does not exist, so exception occurs.
  3. Final Answer:

    KeyNotFoundException at runtime -> Option D
  4. Quick Check:

    Indexer access missing key throws exception [OK]
Quick Trick: Indexer throws exception if key missing [OK]
Common Mistakes:
MISTAKES
  • Expecting default value 0 for missing key
  • Thinking code fails to compile
  • Assuming null is returned for int value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes