0
0
C Sharp (C#)programming~5 mins

Collection initialization syntax in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Avar fruits = new List<string> { "apple", "banana" };
Bvar fruits = new List<string>("apple", "banana");
Cvar fruits = new List<string>.Add("apple", "banana");
Dvar fruits = new List<string> = { "apple", "banana" };
What method must a class have to support collection initialization syntax?
AStart()
BInit()
CCreate()
DAdd()
How do you initialize a Dictionary with keys "x" and "y" and values 10 and 20 respectively?
Avar dict = new Dictionary<string, int> { "x": 10, "y": 20 };
Bvar dict = new Dictionary<string, int> { ("x", 10), ("y", 20) };
Cvar dict = new Dictionary<string, int> { {"x", 10}, {"y", 20} };
Dvar dict = new Dictionary<string, int> { "x" => 10, "y" => 20 };
What will happen if you try to use collection initialization syntax on a class without an Add method?
AIt will work fine
BCompile error
CRuntime error
DIt will ignore the initialization
Which of these is NOT a benefit of collection initialization syntax?
AAutomatically sorts the collection
BShorter code
CEasier to read
DCombines creation and filling
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.