Philip Pittle
Philip Pittle

Reputation: 12295

Return (null) instead of return null - why parenthesis?

I was looking at some MSDN Documentation on IXmlSerializable and the Example Code listed the following method:

public XmlSchema GetSchema()
{
    return(null);
}

Is there a semantic difference between return null and return (null), ie does it invoke some compiler optimization, or is it purely stylistic?

Upvotes: 3

Views: 319

Answers (3)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

No difference, no compiler optimization.

See also e.g. Does using parentheses around return values provide any compiler-related benefits?

Upvotes: 1

user1726343
user1726343

Reputation:

As a general rule, if two statements are semantically equivalent (but syntactically different), any proper compiler will apply the same optimization to both of them. Since C# doesn't specify any difference between the meaning of return null; and return(null);, any hypothetical compiler optimizations that would apply to one would apply to the other.

Upvotes: 1

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

Is there a semantic difference between return null and return (null)

As a whole statement, there isn't any difference. In this case the parentheses are redundant.

does it invoke some compiler optimization

Not at all.

is it purely stylistic?

Most likely, the example comes from an auto-generated code. In such scenarios, when generating an arbitrary expression the generator doesn't know in which context the expression will be used. Hence the easiest thing to do to protect the original intent is wrapping the expression being generated into parentheses. This makes sure it is understood as an 'atomic subexpression' in its surrounding context.

Consider the generator would output a+b and the caller would need to multiply it by c. The wrong way would be to plainly concatenate a+b and *c leading to a+b*c which is obviously wrong. However, when the nested generator returns (a+b), the whole construct is working as intended without any complex decision-making: (a+b)*c.

Note that modern code genrators usually work on expression trees with multi-pass processing instead of passing strings around, so it is much easier for them to eliminate redundant parentheses, making the result more readable by us, humans.

Upvotes: 4

Related Questions