I was updating one of our projects to C# 6.0 when I found a method that was literally doing nothing:
private void SomeMethod()
{
return;
}
Now I was wondering if there is any possibility to rewrite it as an expression-bodied method as it just contains return
.
Try 1:
private void SomeMethod() => return;
Exceptions:
; expected
Invalid token 'return' in class, struct, or interface member declaration
Invalid expression term 'return'
Try 2:
private void SomeMethod() => ;
Exception:
- Invalid expression term ';'
Is there any possibility to achieve this (although this method doesn't really make sense)?
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 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.
Expression-bodied members provide a minimal and concise syntax to define properties and methods. It helps to eliminate boilerplate code and helps writing code that is more readable. The expression-bodied syntax can be used when a member's body consists only of one expression.
That's not an expression body, but you can do this:
private void SomeMethod() { }
If you really want to do expression for body on void function, you can do this:
private void SomeFunction() => Expression.Empty();
This uses Linq and creates an empty expression that has Void type.
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