Inside Man
Inside Man

Reputation: 4319

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.

Upvotes: 1

Views: 154

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504004

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, i.e., 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.

Upvotes: 3

fubo
fubo

Reputation: 46005

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

Upvotes: 1

Related Questions