Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between return myVar vs. return (myVar)?

Tags:

syntax

c#

I was looking at some example C# code, and noticed that one example wrapped the return in ()'s.

I've always just done:

return myRV; 

Is there a difference doing:

return (myRV); 
like image 641
chris Avatar asked Feb 02 '10 18:02

chris


1 Answers

UPDATE: This question was the subject of my blog on 12 April 2010. Thanks for the amusing question!

In practice, there is no difference.

In theory there could be a difference. There are three interesting points in the C# specification where this could present a difference.

First, conversion of anonymous functions to delegate types and expression trees. Consider the following:

Func<int> F1() { return ()=>1; } Func<int> F2() { return (()=>1); } 

F1 is clearly legal. Is F2? Technically, no. The spec says in section 6.5 that there is a conversion from a lambda expression to a compatible delegate type. Is that a lambda expression? No. It's a parenthesized expression that contains a lambda expression.

The Visual C# compiler makes a small spec violation here and discards the parenthesis for you.

Second:

int M() { return 1; } Func<int> F3() { return M; } Func<int> F4() { return (M); } 

F3 is legal. Is F4? No. Section 7.5.3 states that a parenthesized expression may not contain a method group. Again, for your convenience we violate the specification and allow the conversion.

Third:

enum E { None } E F5() { return 0; } E F6() { return (0); } 

F5 is legal. Is F6? No. The spec states that there is a conversion from the literal zero to any enumerated type. "(0)" is not the literal zero, it is a parenthesis followed by the literal zero, followed by a parenthesis. We violate the specification here and actually allow any compile time constant expression equal to zero, and not just literal zero.

So in every case, we allow you to get away with it, even though technically doing so is illegal.

like image 159
Eric Lippert Avatar answered Sep 18 '22 13:09

Eric Lippert