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.

Leave a Comment