Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q14 of 15
C Sharp (C#) - Collections
Identify the error in this code snippet:
var dict = new Dictionary<string, int>();
dict.Add("a", 1);
dict.Add("a", 2);
Console.WriteLine(dict["a"]);
AKey "a" will be removed automatically
BCompilation error due to missing semicolon
CDuplicate key exception on second Add call
DOutput will be 2 without error
Step-by-Step Solution
Solution:
  1. Step 1: Understand Add method behavior with duplicate keys

    The Add method throws an exception if the key already exists.
  2. Step 2: Analyze the code flow

    The first Add("a", 1) works fine. The second Add("a", 2) tries to add the same key again, causing an exception.
  3. Final Answer:

    Duplicate key exception on second Add call -> Option C
  4. Quick Check:

    Adding duplicate key throws exception [OK]
Quick Trick: Add throws error if key exists; use indexer to overwrite [OK]
Common Mistakes:
MISTAKES
  • Assuming Add overwrites existing keys
  • Expecting no error and value updated
  • Confusing Add with indexer assignment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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