Ajai Ajai - 1 year ago 42
C# Question

Initializing list property without "new List" causes NullReferenceException

using System;
using System.Collections.Generic;

class Parent
{
public Child Child { get; set; }
}

class Child
{
public List<string> Strings { get; set; }
}

static class Program
{
static void Main() {
// bad object initialization
var parent = new Parent() {
Child = {
Strings = { "hello", "world" }
}
};
}
}


The above program compiles fine, but crashes at runtime with Object reference not set to an instance of the object.

If you notice in the above snippet, I have omitted new while initializing the child properties.

Obviously the correct way to initialize is:

var parent = new Parent() {
Child = new Child() {
Strings = new List<string> { "hello", "world" }
}
};


My question is why does the C# compiler not complain when it sees the first construct?

Why is the broken initialization valid syntax?

var parent = new Parent() {
Child = {
Strings = { "hello", "world" }
}
};

Answer Source

The second syntax is valid for readonly properties. If you change the code to initialise the Child and Strings properties in the respective constructors, the syntax works.

class Parent
{
    public Parent()
    {
        Child = new Child();
    }

    public Child Child { get; private set; }
}

class Child
{
    public Child()
    {
        Strings = new List<string>();
    }
    public List<string> Strings { get; private set; }
}

static class Program
{
    static void Main()
    {
        // works fine now
        var parent = new Parent
        {
            Child =
            {
                Strings = { "hello", "world" }
            }
        };

    }
}