C# Language Using collection initializer inside object initializer


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.