Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
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.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

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.

about 4 years ago · Santiago Trujillo Relatório

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

about 4 years ago · Santiago Trujillo Relatório

0

new object() is better.

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda