Bird
0
0

What is wrong with this code snippet?

medium📝 Debug Q14 of 15
C Sharp (C#) - Collections
What is wrong with this code snippet?
var dict = new Dictionary<int, string>();
dict.Add(1, "apple");
dict.Add(1, "banana");
AIt will compile and run without errors
BIt causes a runtime exception due to duplicate key
CIt overwrites the first value with the second
DIt causes a compile-time error
Step-by-Step Solution
Solution:
  1. Step 1: Understand Add() behavior with duplicate keys

    Adding a key that already exists causes a runtime exception.
  2. Step 2: Check code behavior

    Second Add with key 1 throws an ArgumentException at runtime.
  3. Final Answer:

    It causes a runtime exception due to duplicate key -> Option B
  4. Quick Check:

    Duplicate keys cause runtime error [OK]
Quick Trick: Add() fails if key exists; use indexer to overwrite [OK]
Common Mistakes:
MISTAKES
  • Assuming Add overwrites existing key
  • Expecting compile-time error instead of runtime
  • Confusing Add with indexer behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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