Reputation: 7656
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)?
Upvotes: 11
Views: 1890
Reputation: 73
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.
Upvotes: 6
Reputation:
Methods which do nothing still make sense - they just do nothing.
You can lose the return statement:
private void SomeMethod() { }
Or assign a function to a variable instead:
private Action SomeMethod = () => { };
Upvotes: 4
Reputation: 39007
That's not an expression body, but you can do this:
private void SomeMethod() { }
Upvotes: 11