Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we use expression-bodied constructors?

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?

like image 688
Gigi Avatar asked Jan 27 '15 10:01

Gigi


People also ask

What is an expression-bodied method?

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.

Which operator can you use to code an expression-bodied property or method?

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.

Can C# expression-bodied method contain multiple expression?

Yes, you can.

Which is correct syntax for expression-bodied function?

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.


2 Answers

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.

like image 192
i3arnon Avatar answered Sep 30 '22 11:09

i3arnon


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

like image 30
Krzysztof Wrona Avatar answered Sep 30 '22 10:09

Krzysztof Wrona