Recall & Review
beginner
What is collection initialization syntax in C#?
It is a way to create and fill a collection (like a list or dictionary) in one simple step using curly braces {} with values inside.
Click to reveal answer
beginner
How do you initialize a List of integers with values 1, 2, and 3 using collection initialization syntax?
You write:
var numbers = new List<int> { 1, 2, 3 }; This creates the list and adds the numbers in one line.Click to reveal answer
intermediate
Can you use collection initialization syntax with dictionaries? How?
Yes. You use curly braces with key-value pairs inside, like:
var dict = new Dictionary { {"a", 1}, {"b", 2} };Click to reveal answer
intermediate
What happens if you try to use collection initialization syntax on a class without an Add method?It will cause a compile error because collection initialization requires the class to have an Add method to add items.Click to reveal answer
beginner
Why is collection initialization syntax useful?
It makes code shorter and easier to read by combining creation and filling of collections in one step.
Click to reveal answer
Which of the following is the correct way to initialize a List of strings with "apple" and "banana" using collection initialization syntax?
✗ Incorrect
Option A uses the correct syntax with curly braces and values inside to initialize the list.
What method must a class have to support collection initialization syntax?
✗ Incorrect
The Add() method is required to add items during collection initialization.
How do you initialize a Dictionary with keys "x" and "y" and values 10 and 20 respectively?
✗ Incorrect
Option C uses the correct syntax with nested braces for key-value pairs.
What will happen if you try to use collection initialization syntax on a class without an Add method?
✗ Incorrect
Without Add(), the compiler cannot add items, so it causes a compile error.
Which of these is NOT a benefit of collection initialization syntax?
✗ Incorrect
Collection initialization does not sort the collection automatically.
Explain how collection initialization syntax works in C# and give an example with a List.
Think about how you can write less code to make a list with items.
You got /3 concepts.
Describe the requirements for a class to support collection initialization syntax.
What method does the compiler call to add items?
You got /3 concepts.