Using collection initializer inside object initializer

suggest change
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 syntactic sugar over calls to Add(). There’s no new list being created here; the compiler is just generating calls to Add() on the existing object.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents