gonzobrains
gonzobrains

Reputation: 8036

Can you use the "return" statement in C# methods declared as void?

While reading an MCSD study guide, I noticed the author said it was illegal to include a return statement in a method that declares the return type void. However, when I created the following method Visual Studio didn't flag it in the editor nor did it fail to compile:

private void ReturnNothing()
{
    return;
}

What is the real answer then? Is this legal?

Upvotes: 2

Views: 4201

Answers (2)

Mario Rossi
Mario Rossi

Reputation: 7799

The author was probably referring to the form

return value ;

which is effectively invalid when return type == void (but valid and required when return type != void).

Upvotes: 0

dcaswell
dcaswell

Reputation: 3167

Yes it's definitely legal.

It's only illegal if you try to put a value after the return. This is wrong return 0;

Upvotes: 10

Related Questions