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?
An expression-bodied method consists of a single expression that returns a value whose type matches the method's return type, or, for methods that return void , that performs some operation.
The expression-bodied syntax can be used when a member's body consists only of one expression. It uses the =>(fat arrow) operator to define the body of the method or property and allows getting rid of curly braces and the return keyword. The feature was first introduced in C# 6.
Yes, you can.
The Syntax of expression body definition is, member => expression; where expression should be a valid expression and member can be any from above list of type members.
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.
Now that the c# 7.0 has been released it is possible to use expression-bodied constructors.
private DbManager() => Console.WriteLine("ctor");
works fine in c# 7.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With