← Back to C# Course | Chapter 9: Collections | Lesson 7 of 7

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:

  1. Collection Initializers
Syntax
csharp
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

markup
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"]);
    }
}
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
  1. Writing List<int> numbers = { 1, 2, 3 }; without new List<int>, which is a compile error because the braces alone only work for arrays.
  2. Putting the same key twice in a Dictionary collection initializer like { { "a", 1 }, { "a", 2 } }, which calls Add twice and throws an ArgumentException.
  3. Thinking an initializer makes the collection fixed or read-only, when it just calls Add for you and the collection can still be changed later.
Chapter Summary
  • Arrays, List<T>, Dictionary<K,V>, and HashSet<T> store groups of values in different ways.
  • Queue and Stack handle 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.