Constructor vs Object Initializer Precedence in C#

不羁岁月 提交于 2019-12-02 18:42:14

From the documentation:

The compiler processes object initializers by first accessing the default instance constructor and then processing the member initializations.

This means that in the simplest case (named object initialization) it is basically shorthand (or syntactic sugar) for calling the default constructor and then calling the property setter(s). In the case of anonymous types this kind of initialization is actually required and not mere sugar.

For the 2nd part of your question: It's more of a matter of style but if you have a crucial property I would not create a constructor with a default value. Make the client code set the value explicitly. I'm also not sure why doing something like this: b = A(true) {foo = false}; would be a good idea unless you're in a code obfuscation contest.

Bit of caution though:

... if the default constructor is declared as private in the class, object initializers that require public access will fail.

Tamim Al Manaseer

Object initializers are just syntactic sugar, in your compiled assembly IL they translate into separate statements, check it on ILSpy.

The constructor occurs first then the object initializer. Just remember that

a = new A() { foo = false };

is same as

var temp = new A();
temp.foo = false;
a = temp;
b = new A(true) {foo = false};

is effectively short for:

A temp = new A(true);
temp.foo = false;
A b = temp;

where temp is an otherwise inaccessible variable. The constructor is always executed first, followed by any initialised properties.

Essentially what Paul has already linked:

From the C# 5 language specification (7.6.10.1)

Processing of an object creation expression that includes an object initializer or
collection initializer consists of first processing the instance constructor and then
processing the member or element initializations specified by the object initializer or
collection initializer.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!