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

Collection Initializers

In this page:

  1. Collection Initializers

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"]);
    }
}
🔒

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.