Bird
Raised Fist0

Identify the issue in this C# code snippet:

medium📝 Debug Q6 of Q15
C Sharp (C#) - Collections
Identify the issue in this C# code snippet:
var dict = new Dictionary<string, int>();
dict["key"] = 1;
dict.Add("key", 2);
ANo error, code runs fine
BThrows exception due to duplicate key
CCompilation error due to syntax
DThe value for "key" is overwritten silently
Step-by-Step Solution
Solution:
  1. Step 1: Analyze dictionary operations

    dict["key"] = 1; adds or updates the key "key" with value 1.
  2. Step 2: dict.Add("key", 2);

    Add throws an exception if the key already exists.
  3. Final Answer:

    Throws exception due to duplicate key -> Option B
  4. Quick Check:

    Adding duplicate key with Add causes exception. [OK]
Quick Trick: Add throws on duplicate keys, indexer overwrites [OK]
Common Mistakes:
MISTAKES
  • Assuming Add overwrites existing key
  • Confusing indexer and Add behavior
  • Expecting no exception on duplicate Add

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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