I don’t understand why such a code can’t build:
if (SomeCondition) {
Boolean x = true;
} else {
Boolean x = false;
}
Debug.WriteLine(x); // Line where error occurs
It creates the following error:
The name ‘x’ does not exist in the current context
For me, x is declared in all cases because there is an else clause. So why the compiler don’t know it on the Debug.WriteLine line?
It is due to block scoping of variables:
{ int x = 3; }is only visible inside the block. You should move the declaration ofxoutside the block:Or in the above case, even better: