New C # 6 object initializer syntax?

I just noticed that in C # written in Visual Studio 2015, the following is possible: but I have never seen it before:

public class X { public int A { get; set; } public YB { get; set; } } public class Y { public int C {get; set; } } public void Foo() { var x = new X { A = 1, B = { C = 3 } }; } 

My expectation was that Foo should be implemented as follows:

 public void Foo() { var x = new X { A = 1, B = new Y { C = 3 } }; } 

Note that there is no need to call new Y

Is this new in C # 6? I did not see mention of this in the notes, so maybe he was always there?

+7
c # roslyn
source share
2 answers

When you run this code, you will get a NullReferenceException.

It will not create an instance of Y , it will call the getter of the XB property and try to assign a value to the C property.

He always worked like that. According to the C # 5.0 language specification:

The initializer of the element that indicates the initializer of the object after the equal sign is the initializer of the nested object, that is, the initialization of the embedded object. Instead of assigning a new value to a field or property, assignments in the initializer of nested objects are considered as assignments to members of a field or property.

+11
source share

This feature was introduced in C # 3.0 as object initializers.

See the example on page 169 C # Language 3.0 Specification :

 Rectangle r = new Rectangle { P1 = { X = 0, Y = 1 }, P2 = { X = 2, Y = 3 } }; 

which has the same effect as

 Rectangle __r = new Rectangle(); __r.P1.X = 0; __r.P1.Y = 1; __r.P2.X = 2; __r.P2.Y = 3; Rectangle r = __r; 
+6
source share

All Articles