Some coders will wrap each condition in its own parentheses, like this:
Style #1:
bool Test(string a, string b)
{
return ((a != null) && (b != null));
}
Style #2:
bool Test(string a, string b)
{
return a != null && b != null;
}
In C# the difference is purely stylistic (at least, I think so). The first expression evaluates first, and the second expression evaluates only if the first is true (otherwise it short-circuits because the entire expression is already confirmed false).
Someone mentioned that #1 above is an "old C style". What is its practical purpose? Is there any actual difference between the two, or is it some kind of safeguard against typos (like writing if (true == x) instead of if (x == true)).
I think this is just defensive coding so the writer of the code (and more importantly, future readers) do not have any doubts about the intent and function of the code.
A long time ago I spent many tedious evenings working through code with a colleague who refused to bracket terms due to his unfailing belief in his ability to remember precedence rules. Despite many examples to the contrary. Even when you know those rules yourself it is easier to read code where the intent is crystal clear, rather than double-checking every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With