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" }
}
};
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…