What is the reason why C# 3.0 introduced optional parentheses in object initializer constructors?
As a syntactic sugar, C# 3.0 allows omitting parentheses in constructor calls in object initializers, provided a parameterless constructor is present. For example:
<code class="language-c#">var x = new XTypeName { PropA = value, PropB = value }; // 括号可选</code>
Reasons for optional brackets
The C# team decided to make parentheses optional based on the following considerations:
Why not make parentheses optional in all default constructor calls?
Introducing optional parentheses in the general case may create semantic ambiguity, as in the following example:
<code class="language-c#">class P { class B { public class M { } } class C : B { new public void M(){} } static void Main() { new C().M(); // 1 new C.M(); // 2 } }</code>
In this case, line 1 calls C's default constructor and then calls instance method M, while line 2 creates a new instance of B.M and calls its default constructor. Making the parentheses optional in line 1 causes ambiguity, forcing the compiler to introduce complex rules to resolve it. The potential cost of this additional complexity outweighs the benefit of optional parentheses in this case.
The above is the detailed content of Why Are Parentheses Optional in C# 3.0 Object Initializer Constructors?. For more information, please follow other related articles on the PHP Chinese website!