Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New C# 6 object initializer syntax?

Tags:

c#

roslyn

c#-6.0

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

public class X
{
    public int A { get; set; }

    public Y B { 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 for Foo to have to be implemented like this:

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 haven't seen any mention of this in the release notes, so maybe it's always been there?

like image 810
jonnystoten Avatar asked Oct 01 '15 22:10

jonnystoten


People also ask

What is the latest Benz 2022?

Mercedes-Benz's entry-level sports sedan has been thoroughly redesigned for the 2022 model year but the C-class sticks with its winning formula of luxury and prestige at an affordable price. The modernization gives the C-class what it needs to better battle rivals such as the Audi A4, BMW 3-series, and Genesis G70.

How much is the latest Benz 2022?

How Much Does the Mercedes-Benz C-Class Cost? The 2022 C-Class sedan starts at $43,550. The midtier Exclusive model starts at $45,800, and the top Pinnacle trim has a starting MSRP of $47,500. All-wheel drive is available in all models for an additional $2,000.

Is the new C-Class FWD?

The C-Class, of course, retains its rear wheel drive layout and there's an updated four-link suspension at the front and the multi-link rear gets a chassis-mounted subframe.

Is C200 a good car?

The 2022 Mercedes-Benz C200 is as much a step forward for the C-Class, as it is for the compact executive category. You get the most car you've ever had with the W206, as Mercedes-Benz pushes forward with an even more up-market skew to their product line. It looks great, and the technology implementation is excellent.


1 Answers

You will get a NullReferenceException if you run this code.

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

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

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.

like image 51
Jakub Lortz Avatar answered Nov 16 '22 00:11

Jakub Lortz