Essential C# Collection Initializers  Suggest an edit

Using collection initializer inside object initializer

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.


Table Of Contents
22 Enum
25 GUID
27 Collection Initializers
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close