Bird
Raised Fist0

Given a dictionary scores with student names as keys and their scores as values, which code snippet safely retrieves the score for "John" without causing an error if the key is missing?

hard🚀 Application Q15 of Q15
C Sharp (C#) - Collections
Given a dictionary scores with student names as keys and their scores as values, which code snippet safely retrieves the score for "John" without causing an error if the key is missing?
Aint score = scores.ContainsKey("John");
Bint score = scores.GetValueOrDefault("John");
Cint score = scores["John"];
Dscores.TryGetValue("John", out int score);
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe retrieval methods

    Using TryGetValue safely tries to get the value and returns false if key is missing without error.
  2. Step 2: Analyze each option

    int score = scores["John"]; throws an exception if "John" is missing. int score = scores.GetValueOrDefault("John"); is invalid in C# Dictionary (GetValueOrDefault is not standard). scores.TryGetValue("John", out int score); uses TryGetValue correctly. int score = scores.ContainsKey("John"); returns a boolean, not the score.
  3. Final Answer:

    scores.TryGetValue("John", out int score); -> Option D
  4. Quick Check:

    TryGetValue safely gets value [OK]
Quick Trick: Use TryGetValue to avoid errors on missing keys [OK]
Common Mistakes:
MISTAKES
  • Using indexer without checking key existence
  • Confusing ContainsKey with value retrieval
  • Expecting GetValueOrDefault method on Dictionary

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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