Andrey Shchekin
Andrey Shchekin

Reputation: 21599

Is it possible to compile a C# method that has non-void return type, but does not return a value?

Is it possible to somehow compile X M() { /*...*/ } given the following constraints:

  1. You can't add any other modifiers to M.
  2. /*...*/ does not contain return or throw, and you can't change it.
  3. You can't add rewriters to the compiler pipeline.
  4. You can change everything else around M.

It might seem like a nonsensical question, but it is actually valuable for DSLs.
E.g. I could define something like task M() {} which would just denote that it is a task, and have nothing to do with a return value.

Upvotes: 0

Views: 171

Answers (3)

flindeberg
flindeberg

Reputation: 5007

Adding in some additional information from the C# specification.

This first paragraph states that a method must have a return type, or void.

Methods have a (possibly empty) list of parameters, which represent values or variable references passed to the method, and a return type, which specifies the type of the value computed and returned by the method. A method’s return type is void if it does not return a value.

This second paragraph specifies that a method with a non-void return type must have a calculable return expression.

A method can use return statements to return control to its caller. In a method returning void, return statements cannot specify an expression. In a method returning non-void, return statements must include an expression that computes the return value.

Even though the specification does not explicitly state that method must contain a return statement, I believe it implicitly says so.

So no, it is not possible according to the C# specification.

Upvotes: 2

CodeCaster
CodeCaster

Reputation: 151588

So you have a method:

public Foo Bar()
{
    DoX();

    DoY();

    DoZ();
}

Which doesn't compile, because the only path in the method doesn't return anything.

Given your constraints (basically: you have to compile the code as-is, with a standard C# compiler), the answer is: no, you can't make this compile.

Upvotes: 1

Jodrell
Jodrell

Reputation: 35696

maybe,

abstract class Whatever
{
    public abstract X M<X>();
}

Upvotes: 0

Related Questions