简体   繁体   中英

C# What is this initialization doing if it doesn't have the 'new'?

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?

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" } };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM