diiN__________
diiN__________

Reputation: 7656

Expression-bodied method: Return nothing

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

Upvotes: 11

Views: 1890

Answers (3)

Charles Tremblay
Charles Tremblay

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

user1023602
user1023602

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

Kevin Gosse
Kevin Gosse

Reputation: 39007

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

private void SomeMethod() { }

Upvotes: 11

Related Questions