Why does C# not allow me to call a void method as part of the return statement?

Matt Beckman picture Matt Beckman · Jul 10, 2014 · Viewed 11.8k times · Source

I am curious if there is a legitimate reason as to why C# does not support calling a void method as part of the return statement when the calling method's return type is also void.

public void MethodA() 
{ 
    return; 
}

public void MethodB() 
{
    return MethodA();
}

So we would normally see this:

public void MethodMeh() 
{
    if (expression) 
    {
        MethodA();
        return;
    }

    // Do more stuff
}

... when we could be using this instead:

public void MethodAwesome() 
{
    if (expression) 
        return MethodA();

    // Do more stuff
}

Is this a language limitation due to how C# handles void?

Answer

dan04 picture dan04 · Jul 10, 2014

Because it's simply the way the language is defined.

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.

It's an arbitrary decision (presumably made for compatibility with ANSI C and its other descendants), and other languages do things differently.

For example, in Python, all functions return a value. If you execute a return statement without a value, or let control reach the end of the function, then it's just like you had written return None.

In contrast, Pascal limits the terminology of function to subprograms that have a return value; if you don't want to return anything, you use a procedure instead.