Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

79
Views
Why is it not allowed to declare empty expression body for methods?

I had a method which has an empty body like this:

public void Foo()
{
}

As suggested by ReSharper, I wanted to convert it to expression body to save some space and it became:

public void Foo() => ;

which doesn't compile. Is there a specific reason why this is not supported?

And I think I should open a bug ticket for ReSharper since it refactors code to a non-compilable version.

8 months ago · Santiago Trujillo
3 answers
Answer question

0

[EDIT: This answer is not correct, do not use it - see comments.]

As you can see, expression body uses the lambda operator ("=>"). If you still want to write your empty void method as an expression body, you can use Expression.Empty() to show that Foo() is an empty (void) expression.

Methods that return void or Task should be implemented with expressions that don’t return anything, either. (https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/october/csharp-the-new-and-improved-csharp-6-0)

The following code piece should work.

public void Foo() => Expression.Empty();

Also I agree with your last comment that it is a ReSharper bug.

8 months ago · Santiago Trujillo Report

0

From the docs:

An expression body definition has the following general syntax:

member => expression;

where expression is a valid expression.

Also:

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.

So if you want to use expression bodied members, you actually do need ... an expression (Surprise!)

But you can still use the conventional style:

string Property
{
    get => _value;
    set { } // empty
}

void Method() { } // empty

You could create a "no-op" helper, like this:

public static void Noop() {}

string Property
{
    set => Noop();
}

void Method() => Noop();

Another alternative would be GC.KeepAlive(null).

8 months ago · Santiago Trujillo Report

0

new object() is better.

Expression.Empty() really doesn't make any sense.

8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.