I'm missing what/how this even compiles, and what does it try to do:
// throws null reference exception on 'get' for C1:
var c2 = new Class2 { C1 = { Value = "stg" } };
public class Class1
{
public string Value { get; set; }
}
class Class2
{
public Class1 C1 { get; set; }
}
It's obvious that the initialization should include the "new":
var c2 = new Class2 { C1 = new Class1 { Value = "stg" } };
but how is this compiling even without the "new", and what is it trying to do?
CodePudding user response:
Construction
var c2 = new Class2 { C1 = { Value = "stg" } };
is a syntactic sugar which is unfurled into
Class c2 = new Class2();
c2.C1.Value = "stg"; // <- Here we have the exception thrown
It's not evident for compiler, that C1
is null
(C1
can well be created in the constructor) that's why the code compiles.
Edit: Why compiler allow C1 = { Value = "stg" }
? It's convenient (syntactic sugar is for our convenience), imagine:
public class Class1 {
public string Value { get; set; }
}
class Class2 {
// Suppose, that in 99% cases we want C1 with Value == "abc"
// But only when Class1 instance is a property C1 of Class2
public Class1 C1 { get; set; } = new Class1() { Value = "abc" };
}
...
// however, in our particular case we should use "stg":
var c2 = new Class2 { C1 = { Value = "stg" } };
// for some reason I recreate C1 (note "new"):
var otherC2 = new Class2 { C1 = new Class1 { Value = "stg" } };