Friday, December 25, 2015

C# Puzzle: Non-void functions without return statements that will compile successfully

When you try to compile the following function, the C# compiler will complain that "not all code paths return a value".

int MyMethod()
{
}

Of course if you return a value, the compiler will stop complaining. But is it always required to return a value in a non-void function ? Can you compile a non-void function without a return statement ?



Scroll for the answer






















































































































































Answer


Yes, you can..
In C#, the return statement is not required in non-void functions, and can be omitted in two cases (AFAIK).

1. Functions with unreachable endpoint

A function that throws exceptions in all code paths, is an example of a function with an unreachable endpoint, that will compile successfully without a return statement.


int MyExceptionalMethod()
{
    // Do something..
    throw new Exception();
}

Functions with infinite loops are also another type of unreachable endpoint functions, like this one:

int MyInfiniteMethod1()
{
    while (true
    {
       // Do something forever..
    }
}

Or this one:

int MyInfiniteMethod2()
{
    MyLabel:
    // Do something again and again..

    goto MyLabel;
}


2. Async functions that return a Task

async Task MyMethod4()
{
    // await for something..
}


References: