Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not allowed to declare empty expression body for methods?

I had a method which has an empty body like this:

public void Foo()
{
}

As suggested by ReSharper, I wanted to convert it to expression body to save some space and it became:

public void Foo() => ;

which doesn't compile. Is there a specific reason why this is not supported?

And I think I should open a bug ticket for ReSharper since it refactors code to a non-compilable version.

like image 652
Selman Genç Avatar asked Apr 10 '17 00:04

Selman Genç


People also ask

What is an empty expression?

An empty expression can be used where an expression is expected but no action is desired. For example, you can use an empty expression as the last expression in a block expression. In this case, the block expression's return value is void.

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.

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.


1 Answers

[EDIT: This answer is not correct, do not use it - see comments.]

As you can see, expression body uses the lambda operator ("=>"). If you still want to write your empty void method as an expression body, you can use Expression.Empty() to show that Foo() is an empty (void) expression.

Methods that return void or Task should be implemented with expressions that don’t return anything, either. (https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/october/csharp-the-new-and-improved-csharp-6-0)

The following code piece should work.

public void Foo() => Expression.Empty();

Also I agree with your last comment that it is a ReSharper bug.

like image 55
matt.h Avatar answered Sep 30 '22 20:09

matt.h