C# Language Collection Initializers Using collection initializer inside object initializer

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

public class Tag
{
    public IList<string> Synonyms { get; set; }
}

Synonyms is a collection-type property. When the Tag object is created using object initializer syntax, Synonyms can also be initialized with collection initializer syntax:

Tag t = new Tag 
{
    Synonyms = new List<string> {"c#", "c-sharp"}
};

The collection property can be readonly and still support collection initializer syntax. Consider this modified example (Synonyms property now has a private setter):

public class Tag
{
    public Tag()
    {
        Synonyms = new List<string>();
    }
    
    public IList<string> Synonyms { get; private set; }
}

A new Tag object can be created like this:

Tag t = new Tag 
{
    Synonyms = {"c#", "c-sharp"}
};

This works because collection initializers are just syntatic sugar over calls to Add(). There's no new list being created here, the compiler is just generating calls to Add() on the exiting object.



Got any C# Language Question?