0

[Disclaimer]: I know the meaning of "void" and "return". The question is about language syntax and convenience. Please read it to the end before assuming I didn't read any documentation.

I wonder why it's not possible to return the result of a void function, in a one line statement.

For example, the following code example does not compile:

class Program
{
    static void Main(string[] args)
    {
        return Usage(); // fails
    }

    static void Usage()
    {
    }
}

throwing:

error CS0127: Since 'DProgram.Main(string[])' returns void, a return keyword must not be followed by an object expression

I obviously can split in two lines like

Usage();
return;

But it would be convenient to have the one-line statement.

In the generated MSIL (of the correct splitted version),

I can see:

.method private hidebysig static 
    void Main (
        string[] args
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 6 (0x6)
    .maxstack 8
    .entrypoint

    IL_0000: call void DirectoryCompileAndRun.Program::Usage()
    IL_0005: ret
} // end of method Program::Main

Which is exactly what would be generated if both methods (Main and Usage) did return the same non-empty type. So obviously the reason is not related to intermediate representation, but purely to C# design.

Does anyone here knows the reason for this compiler "limitation"?

Regis Portalez
  • 4,675
  • 1
  • 29
  • 41

0 Answers0