New C# 6 object initializer syntax?

依然范特西╮ 提交于 2019-12-05 06:53:26

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.

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

See example on p. 169 of 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;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!