Bird
Raised Fist0

Which of the following is the correct syntax to initialize a dictionary with keys and values in C#?

easy📝 Syntax Q12 of Q15
C Sharp (C#) - Collections
Which of the following is the correct syntax to initialize a dictionary with keys and values in C#?
Avar dict = new Dictionary<int, string> { 1: "One", 2: "Two" };
Bvar dict = new Dictionary<int, string> (1: "One", 2: "Two");
Cvar dict = new Dictionary<int, string> { (1, "One"), (2, "Two") };
Dvar dict = new Dictionary<int, string> { {1, "One"}, {2, "Two"} };
Step-by-Step Solution
Solution:
  1. Step 1: Recall dictionary initialization syntax

    Dictionaries use curly braces with key-value pairs inside another set of braces: { {key, value}, ... }.
  2. Step 2: Check each option

    var dict = new Dictionary { {1, "One"}, {2, "Two"} }; uses correct syntax with nested braces for each pair. Others use invalid syntax for C# dictionaries.
  3. Final Answer:

    var dict = new Dictionary { {1, "One"}, {2, "Two"} }; -> Option D
  4. Quick Check:

    Dictionary init = nested braces for pairs [OK]
Quick Trick: Use double braces for dictionary key-value pairs [OK]
Common Mistakes:
MISTAKES
  • Using colon instead of comma between key and value
  • Trying to use parentheses instead of braces
  • Confusing dictionary syntax with object initializers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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