Collection Initializers in C#

What are Collection Initializers in C#?

**Collection Initializers** in C# provide a concise way to initialize collections at the time of declaration. They allow adding multiple elements to a collection without explicitly calling the Add() method.

Key Features of Collection Initializers

  • Allows **inline initialization** of collections.
  • Works with **any collection type** that implements ICollection<T>.
  • Reduces boilerplate code by eliminating multiple Add() calls.
  • Can be used with **custom collection classes** that provide an Add method.

Using Collection Initializers in C#

Collection initializers simplify the process of initializing collections, as shown below.

Example: Initializing a List with Collection Initializers

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initializing a List using Collection Initializers
        List names = new List { "Alice", "Bob", "Charlie", "David" };

        Console.WriteLine("Names in the List:");
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

// Output:
// Names in the List:
// Alice
// Bob
// Charlie
// David
        

The List<T> is initialized with values using **collection initializers**, eliminating multiple Add() method calls.

Using Collection Initializers with Dictionary

Collection initializers can also be used with **Dictionary** to initialize key-value pairs.

Example: Initializing a Dictionary with Collection Initializers

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initializing a Dictionary using Collection Initializers
        Dictionary employees = new Dictionary
        {
            { 101, "Alice" },
            { 102, "Bob" },
            { 103, "Charlie" }
        };

        Console.WriteLine("Employee List:");
        foreach (var emp in employees)
        {
            Console.WriteLine($"ID: {emp.Key}, Name: {emp.Value}");
        }
    }
}

// Output:
// Employee List:
// ID: 101, Name: Alice
// ID: 102, Name: Bob
// ID: 103, Name: Charlie
        

The **Dictionary** is initialized using key-value pairs in a compact and readable format.

Using Collection Initializers with Custom Collections

A **custom collection** can also support collection initializers if it provides an Add method.

Example: Using Collection Initializers in a Custom Collection

using System;
using System.Collections;
using System.Collections.Generic;

class StudentCollection : IEnumerable
{
    private List students = new List();

    public void Add(string name)
    {
        students.Add(name);
    }

    public IEnumerator GetEnumerator() => students.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

// Usage
class Program
{
    static void Main()
    {
        // Initializing custom collection
        StudentCollection students = new StudentCollection { "Alice", "Bob", "Charlie" };

        Console.WriteLine("Students:");
        foreach (var student in students)
        {
            Console.WriteLine(student);
        }
    }
}

// Output:
// Students:
// Alice
// Bob
// Charlie
        

The **custom collection** supports collection initializers by defining an Add method.

Best Practices for Using Collection Initializers

  • Use collection initializers for **concise and readable** code.
  • Prefer collection initializers for **small and predefined** collections.
  • Ensure **custom collections implement Add method** for initializer support.
  • Use **Dictionary initializers** for better readability of key-value pairs.