I have trouble understanding what the following code means (and partly, why it even compiles).
We have the following snippet:
if (true) return;
{
... // Unreachable code detected
}
Why does this even compile?
Am I correct in thinking that the compiler assumes an else in this construct? If not, how does it work?
I think it must be logically equivalent to
if (true)
return;
else
{
...; // Unreachable code detected.
}
I’m in doubt, because the compiler doesn’t seem to interpret the following as an if-else
if (condition)
{
...
}
{
...
}
It does compile, but the second block gets executed no matter what.
Is this behavior explicitly stated in the C# specs?
It doesn’t assume an
elsehere, it’s just that any code of the form:is logically equivalent to:
Because
code Bwill only ever be reached ifconditionevaluates to false.Your confusion might also be coming from having a braced block of code that is not preceded by a keyword.
This is perfectly legal; code blocks do not require control flow keywords, and you can nest your code within braces wherever you like. While it’s not terribly common, it’s legal. Note that it does create a new variable scope in your code, and (just like all other code blocks) code outside of these blocks will not be able to access any variables declared within the block.
For example:
While not advisable, you could use this to declare two identically-named but different variables: