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.
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.
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.
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.
[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.
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