Initializing list property without "new List" causes NullReferenceException
It's not broken syntax, it's you who uses an object initializer on a property that's simply not instantiated. What you wrote can be expanded to
var parent = new Parent();
parent.Child.Strings = new List<string> { "hello", "world" };
Which throws the NullReferenceException
: you're trying to assign the property Strings
contained by the property Child
while Child
is still null
.
Using a constructor to instantiate Child
first, takes care of this.
There is nothing wrong with the initialisation, but it's trying to initialise objects that doesn't exist.
If the classes have constructors that create the objects, the initialisation works:
class Parent {
public Child Child { get; set; }
public Parent() {
Child = new Child();
}
}
class Child {
public List<string> Strings { get; set; }
public Child() {
Strings = new List<string>();
}
}
You seem to misunderstand what the collection initializer does.
It is a mere syntactic sugar that converts the list in the braces into a series of calls to Add()
method that must be defined on the collection object being initialized.
Your = { "hello", "world" }
is therefore has the same effect as
.Add("hello");
.Add("world");
Obviously this will fail with a NullReferenceException if the collection is not created.