Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Using Collection Initialization Syntax in C#
📖 Scenario: You are building a simple inventory system for a small bookstore. You want to store a list of book titles available in the store.
🎯 Goal: Create a list of book titles using collection initialization syntax, then add a few more titles, and finally display all the titles.
📋 What You'll Learn
Create a List<string> called books with three specific book titles using collection initialization syntax.
Add two more book titles to the books list.
Use a foreach loop to print each book title.
💡 Why This Matters
🌍 Real World
Managing collections of items like books, products, or users is common in software applications.
💼 Career
Understanding collection initialization and manipulation is essential for software developers working with data storage and retrieval.
Progress0 / 4 steps
1
Create a list of books using collection initialization syntax
Create a List<string> called books and initialize it with these exact book titles: "The Hobbit", "1984", and "Pride and Prejudice" using collection initialization syntax.
C Sharp (C#)
Hint
Use new List<string> { ... } to initialize the list with values.
2
Add more books to the list
Add two more book titles to the books list: "To Kill a Mockingbird" and "The Great Gatsby" using the Add method.
C Sharp (C#)
Hint
Use books.Add("Book Title") to add new titles.
3
Print all book titles using a foreach loop
Use a foreach loop with the variable book to iterate over books and print each book title using Console.WriteLine(book).
C Sharp (C#)
Hint
Use foreach (string book in books) to loop through the list and Console.WriteLine(book) to print each title.
4
Run the program to display all book titles
Run the program to display all the book titles in the console. The output should list all five books, each on its own line.
C Sharp (C#)
Hint
Make sure your program prints each book title on its own line.
Practice
(1/5)
1. What does collection initialization syntax in C# allow you to do? var list = new List<int> { 1, 2, 3 };
easy
A. Only create an empty collection
B. Create and fill a collection in one step
C. Fill a collection after creating it separately
D. Create a collection without specifying type
Solution
Step 1: Understand collection initialization
Collection initialization lets you create a collection and add items to it in one line.
Step 2: Analyze the example code
The code new List<int> { 1, 2, 3 } creates a list and fills it with 1, 2, and 3 immediately.
Final Answer:
Create and fill a collection in one step -> Option B
Quick Check:
Collection initialization = create + fill [OK]
Hint: Remember: initialization means create and fill together [OK]
Common Mistakes:
Thinking it only creates empty collections
Confusing initialization with adding items later
Assuming type is optional in initialization
2. Which of the following is the correct syntax to initialize a dictionary with keys and values in C#?
easy
A. var dict = new Dictionary { 1: "One", 2: "Two" };
B. var dict = new Dictionary (1: "One", 2: "Two");
C. var dict = new Dictionary { (1, "One"), (2, "Two") };
D. var dict = new Dictionary { {1, "One"}, {2, "Two"} };
Solution
Step 1: Recall dictionary initialization syntax
Dictionaries use curly braces with key-value pairs inside another set of braces: { {key, value}, ... }.
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.
Final Answer:
var dict = new Dictionary { {1, "One"}, {2, "Two"} }; -> Option D
Quick Check:
Dictionary init = nested braces for pairs [OK]
Hint: Use double braces for dictionary key-value pairs [OK]
Common Mistakes:
Using colon instead of comma between key and value
Trying to use parentheses instead of braces
Confusing dictionary syntax with object initializers
3. What will be the output of the following C# code?
var set = new HashSet<int> { 1, 2, 2, 3 };
Console.WriteLine(set.Count);
medium
A. 3
B. Runtime error
C. 2
D. 4
Solution
Step 1: Understand HashSet behavior
A HashSet stores unique elements only, so duplicates are ignored.
Step 2: Analyze the initialization
The set is initialized with {1, 2, 2, 3}, but the duplicate '2' is ignored, so the set contains 3 unique elements.
Final Answer:
3 -> Option A
Quick Check:
HashSet ignores duplicates = count 3 [OK]
Hint: HashSet counts unique items only [OK]
Common Mistakes:
Counting duplicates as separate elements
Expecting a runtime error due to duplicates
Confusing HashSet with List behavior
4. Identify the error in this collection initialization:
var list = new List<int> { 1, 2, "3" };
medium
A. Using parentheses instead of braces
B. Missing semicolon at the end
C. Mixing int and string types in List<int>
D. List cannot be initialized with values
Solution
Step 1: Check the List type and values
The list is declared as List<int>, so all elements must be integers.
Step 2: Identify the incorrect value
The value "3" is a string, not an int, causing a type mismatch error.
Final Answer:
Mixing int and string types in List<int> -> Option C
Quick Check:
List<int> must contain only ints [OK]
Hint: All items must match the collection's declared type [OK]
Common Mistakes:
Assuming implicit conversion from string to int
Ignoring type mismatch errors
Thinking semicolon or braces are the problem
5. You want to initialize a dictionary where keys are strings and values are lists of integers. Which is the correct way to do this in C#?
hard
A. var dict = new Dictionary { { "a", new List<int> {1, 2} }, { "b", new List<int> {3, 4} } };
B. var dict = new Dictionary { { "a", {1, 2} }, { "b", {3, 4} } };
C. var dict = new Dictionary { ( "a", [1, 2] ), ( "b", [3, 4] ) };
D. var dict = new Dictionary { "a": [1, 2], "b": [3, 4] };
Each dictionary value is a List<int>, so you must create new List<int> instances inside the dictionary initializer.
Step 2: Check syntax correctness
var dict = new Dictionary { { "a", new List<int> {1, 2} }, { "b", new List<int> {3, 4} } }; correctly uses nested initializers: dictionary with key-value pairs, where values are new List<int> with their own initializers.
Final Answer:
var dict = new Dictionary { { "a", new List<int> {1, 2} }, { "b", new List<int> {3, 4} } }; -> Option A
Quick Check:
Nested collections need explicit new List<int> [OK]
Hint: Use 'new' for nested collections inside dictionary [OK]