0 Comments
  •   Posted in: 
  • C#

I came across this syntax recently where it looked like a C# collection was being initialized without the “new” keyword.

For example, if we have a class:

{
    public ICollection<string> PrivateNames { get; } = new List<string> { "Mike" };

    public Names()
    {  }
}

This was being used as:

var names = new Names
{
    PrivateNames = { "Steve", "John" }
};

In fact, this is not a collection initializer at all.  It is shorthand ( syntactic sugar ) for appending items to a collection.

This test shows the appending behaviour:

[Test]
public void InitializerWithoutNewAddsNames()
{
    var names = new Names
    {
        PrivateNames = { "Steve", "John" }
    };

    Assert.AreEqual("Mike, Steve, John", string.Join(", ", names.PrivateNames));
}

Note: it is quite a specific shortcut.  The collection must already have been created and it only works when creating a new instance.

If you try to use the syntax outside of the new statement, eg

names.PrivateNames = { "Sarah", "Jenny"};

this will not compile.

Post comment