C# object initialization of read only collection properties

This:

MyClass c = new MyClass
{
    StringCollection = { "test2", "test3" }
};

is translated into this:

MyClass tmp = new MyClass();
tmp.StringCollection.Add("test2");
tmp.StringCollection.Add("test3");
MyClass c = tmp;

It’s never trying to call a setter – it’s just calling Add on the results of calling the getter. Note that it’s also not clearing the original collection either.

This is described in more detail in section 7.6.10.3 of the C# 4 spec.

EDIT: Just as a point of interest, I was slightly surprised that it calls the getter twice. I expected it to call the getter once, and then call Add twice… the spec includes an example which demonstrates that.

Leave a Comment