11

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)?

Community
  • 1
  • 1
diiN__________
  • 7,393
  • 6
  • 42
  • 69

3 Answers3

10

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

private void SomeMethod() { }
Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
3

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 = () => { };
Community
  • 1
  • 1
  • Your second example does not compile. `private Action SomeMethod = () => { };` does, but I think it's a bad idea. – svick Jun 20 '16 at 14:00
  • Thanks, i have updated the answer. Yes its a bad idea, I had never done it before and guessed wrong. –  Jun 20 '16 at 14:08
  • I noticed you *can* do this: `private void NOPMethod(){} private void SomeMethod() => NOPMethod();` – Tom Dec 13 '18 at 03:16
3

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.

Pang
  • 9,564
  • 146
  • 81
  • 122