I've inherited some code that makes occasional use of the following if notation:
if (a) foo(); { if (b) boo(); moo(); }
I'm not sure how to read that naturally but the code compiles and runs.
Can someone please explain how this works so that I can rewrite it in more human readable format? Alternatively, could someone explain why this notation could be useful?
The code you've posted would be better written as:
if (a) { foo(); } if (b) { boo(); } moo();
Braces in C# have two purposes:
Whoever wrote the code you've posted chose not to use them for the second purpose. if
statements can be totally legitimate without using any braces, but they'll only apply to the statement that immediately follows them (like the call to foo()
after the first if
).
Because there is a legitimate use case for braces that has nothing to do with control flow, however, it is perfectly acceptable for someone to put braces in random places that have nothing to do with the if
statements.
This code:
foo(); { var a = boo(); } { var a = moo(); }
... is equivalent to this code:
foo(); var a = boo(); var b = moo();
... but you'll notice that I couldn't name the second variable a
because it's no longer separated from the first variable by scoping braces.
Alternatively, could someone explain why this notation could be useful?
There are three possibilities I can think of:
The first two possibilities assume they're actually doing more than calling foo()
and moo()
in the real production code.
In any case, I don't think any of these possibilities are good reasons to write code like this, and you are totally within your rights to want to rewrite the code in a way that's easier to understand.
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