Please note that it's not a question on how else binds and how the scope stretches. Also, please note, that it's not a question on if we should or shouldn't use curly braces.
Regard the following nested conditional statement.
if(alpha)
if(beta)
AlphaAndBeta();
else
AlphaNotBeta();
Personally, even if I'm a big believer of removing any redundant parenthesis, I'd suggest usage of curly braces in this case to make it abundantly clear that the else statement is a part of the inner condition, which can be tricky to see, especially if some smart-donkey starts horsing around with the indentation like so.
if(alpha)
if(beta)
AlphaAndBeta();
else
AlphaNotBeta();
However, I'd like to have a handy reference to where the behavior is described. I've looked at the language definition on MSDN but haven't found the exact spot. It needs to be super-ultra-clearly stated how the else bind to its if (and doesn't necessarily have to be MS's official site).
Where can I find the page, please?
This is documented in the C# specification, section 8.7.1 - The if
statement:
An
else
part is associated with the lexically nearest precedingif
that is allowed by the syntax. Thus, anif
statement of the formif (x) if (y) F(); else G();
is equivalent to
if (x) { if (y) { F(); } else { G(); } }
Here's one resource, MSDN:
The statement or statements in the then-statement and the else-statement can be of any kind, including another if statement nested inside the original if statement. In nested if statements, each else clause belongs to the last if that doesn’t have a corresponding else.
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