简体   繁体   中英

Populating nested property in object initialization - C#

Here is my code:

MyTool tool = new MyTool(new SubTool());
tool.PrintingSystem.Document.Target = 1;
tool.ShowPreview();

I want to know if it is possible to populate the PrintingSystem.Document.Target in initialization like this:

MyTool tool = new MyTool(new SubTool())
{
   PrintingSystem.Document.Target = 1
};

It does not work currently.

The equivalent of your original code with an object initializer is:

MyTool tool = new MyTool(new SubTool())
{
    PrintingSystem = { Document = { Target = 1 } }
};

This only calls the getters for PrintingSystem and then Document , then calls the setter for Target - just like your original code. This is a relatively rarely-used feature of object initializers, called nested object initializers . From the ECMA C# standard , section 12.7.11.3:

A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (§12.18.2) to the field or property.

A member initializer that specifies an object initializer after the equals sign is a nested object initializer , ie, an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type.

It will only work if PrintingSystem and Document default to non-null values - otherwise you'd need to set the properties as per fubo's answer.

If a property is a object, refering to another object - you have to create a new instance of each to avoid a NullreferenceException

MyTool tool = new MyTool(new SubTool())
{
    PrintingSystem = new PrintingSystem() { Document = new Document() { Target = 1 } }
};

https://dotnetfiddle.net/1G39Zs

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