Collection Initializers
Collection initializers let you create a list and fill it in one go, like packing a lunchbox with all its items at the moment you get it. It saves a lot of repeated adding.
In this page:
Syntax
List<type> list = new List<type> { value1, value2 };
Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>
{
{ key1, value1 },
{ key2, value2 },
};
Collection Initializers
Collection initializer syntax lets you populate an array, list, or dictionary immediately at creation with { ... }, without a separate series of .Add() calls.
It works for any type implementing IEnumerable that has an Add method. This makes setup code much more compact and readable.
Note:
Object and collection initializers combine well — you can initialize a list of custom objects in one expression.
Example: Collection Initializers
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3 };
Dictionary<string, int> scores = new Dictionary<string, int>
{
{ "Al", 10 },
{ "Bo", 20 },
};
Console.WriteLine(numbers.Count);
Console.WriteLine(scores["Bo"]);
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
List<int> numbers = { 1, 2, 3 };withoutnew List<int>, which is a compile error because the braces alone only work for arrays. - Putting the same key twice in a
Dictionarycollection initializer like{ { "a", 1 }, { "a", 2 } }, which callsAddtwice and throws anArgumentException. - Thinking an initializer makes the collection fixed or read-only, when it just calls
Addfor you and the collection can still be changed later.
Chapter Summary
- Arrays,
List<T>,Dictionary<K,V>, andHashSet<T>store groups of values in different ways. QueueandStackhandle first in first out and last in first out order.- LINQ basics and collection initializers query and create collections concisely.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: