It compiles, because compiler has no knowledge about is the List
already initialized somewhere else. You can make it work by adding initialization into a constructor:
public class Container
{
public IList<string> Items { get; set; }
public Container()
{
Items = new List<string>();
}
}
Or changing the property to hide a field, which is initialized when class instance is created:
private IList<string> items = new List<string>();
public IList<string> Items
{
get { return items; }
set { items = value; }
}
Then, var container = new Container() { Items = { "Test" } };
works just fine.
At runtime .Add()
method is called for every item in collection initializer group. When property is not initialized with new List<string>
it has null
value, and that's why NullReferenceException
is thrown.
Object and Collection Initializers (C# Programming Guide)
By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.