Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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?

like image 480
Philip Pittle Avatar asked Jul 27 '26 12:07

Philip Pittle


1 Answers

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.

like image 160
Ondrej Tucny Avatar answered Jul 30 '26 01:07

Ondrej Tucny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!