I've a goto
question: is it possible to go to a label that is down a local scope?
The below code can't find the InsideTrue
label:
goto InsideTrue; // error CS0159: No such label 'InsideTrue' within the scope of the goto statement
if (true)
{
InsideTrue:
Console.WriteLine("true");
goto OutsideIf;
}
else
{
InsideFalse:
Console.WriteLine("false");
goto OutsideIf;
}
OutsideIf:
I would want to use that as a special branching case to bypass the if/else
check on certain circumstances, how can I achieve that, without recompiling?
CodePudding user response:
This is horrible, but to entertain us all, you could extract the code inside the if/else to other labels:
goto InsideTrue;
if (true)
{
goto InsideTrue;
}
else
{
goto InsideFalse;
}
InsideTrue:
Console.WriteLine("true");
goto OutsideIf;
InsideFalse:
Console.WriteLine("false");
OutsideIf:
CodePudding user response:
First you shouldn't use it, but other people already said it so I'll not elaborate on this.
Second the problem that you encounter is that the InsideTrue
declaration is out of the scope at the first line. This is because it hasn't been declared at this position of your code.
You will have to rethink your code to declare InsideTrue
out of the if
(I know this is what you want but it can't be done that way), because at the runtime there's no way to know if you're going to enter the if
, preventing the declaration of InsideTrue
until you're inside it.
Goto (really, stop using it) is used to exit switch statements or loops with a Labeled Statement outside of it, to avoid code that is not required