11
votes

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:

  1. ; expected

  2. Invalid token 'return' in class, struct, or interface member declaration

  3. Invalid expression term 'return'

Try 2:

private void SomeMethod() => ;

Exception:

  1. Invalid expression term ';'

Is there any possibility to achieve this (although this method doesn't really make sense)?

3

3 Answers

9
votes

That's not an expression body, but you can do this:

private void SomeMethod() { }
3
votes

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 = () => { };
1
votes

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.