Using the new Expression-Bodied Members feature in C# 6.0, we can take a method like this:
public void Open()
{
Console.WriteLine("Opened");
}
...and change it to a simple expression with equivalent functionality:
public void Open() => Console.WriteLine("Opened");
This is not true for constructors, however. Code such as this doesn't compile:
private DbManager() => Console.WriteLine("ctor");
Nor does this:
private DbManager() => {}
Is there any reason why constructors cannot benefit from the expression-bodied members feature, and must be declared the traditional way?
It would be more confusing than useful. Especially when you add a call to another constructor.
Here's the direct quote from the design notes:
Constructors have syntactic elements in the header in the form of this(…) or base(…) initializers which would look strange just before a fat arrow. More importantly, constructors are almost always side-effecting statements, and don’t return a value.
From C# Design Notes for Nov 4, 2013
In a more general way:
To summarize, expression bodies are allowed on methods and user defined operators (including conversions), where they express the value returned from the function, and on properties and indexers where they express the value returned from the getter, and imply the absence of a setter.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments