Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression-bodied method: Return nothing

Tags:

c#

c#-6.0

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

like image 585
diiN__________ Avatar asked Jun 20 '16 08:06

diiN__________


People also ask

What is an expression-bodied method?

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.

Which is correct syntax for expression-bodied function?

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.

How to use expression body in c#?

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.


2 Answers

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

private void SomeMethod() { }
like image 132
Kevin Gosse Avatar answered Oct 05 '22 23:10

Kevin Gosse


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.

like image 28
Charles Tremblay Avatar answered Oct 05 '22 23:10

Charles Tremblay