In my program, I have a method that has code that is used always when it is run. However, in the same method, I have if
statements that branches off the code based on a state machine. Let's just (for simplicity) say that it's made of two values.
using System;
using System.Console;
int stateA = 1;
int stateB = 1;
void Main () {
while (true) {
Method();
}
}
void Method () {
Console.WriteLine("This will always be printed no matter what happens.");
if (stateA == 1 && stateB == 1)
{
Console.WriteLine("State 1");
stateB = 2;
// goto endofifstatement;
}
elseif (stateA == 1 && stateB == 2)
{
Console.WriteLine("State 2");
stateA = 2;
// goto endofifstatement;
}
else {
Console.WriteLine("Resetting States...")
stateA = 1;
stateB = 2;
// goto endofifstatement;
}
// endofifstatement:
Console.WriteLine("This will always also be printed no matter what happens.");
Console.WriteLine("");
}
Now. The problem with this code right now, is that all three parts of the if...elseif...else
block will run in every loop iteration.
Of course, there are several ways I could fix this:
- Separate (encapsulate) the
if...elseif....else
statement into its own method and usereturn
to break out. - Swap the contents and expressions for the
if
andelseif
block, but that'd only work in this case. What happens if we have a few hundred cases? - Use
goto
, but nobody really uses that anymore. (Commented in the snippet above) - Use multiple
switch...case
or IF statements, nested inside each other.
Question:
Is it possible to escape out of a if...elseif...else
statement like break
does to a loop and return
does for methods?
So for the example above, the output should be:
This will always be printed no matter what happens.
State 1
This will always also be printed no matter what happens.
This will always be printed no matter what happens.
State 2
This will always also be printed no matter what happens
This will always be printed no matter what happens.
Resetting States...
This will always also be printed no matter what happens
And repeat, as opposed to:
This will always be printed no matter what happens.
State 1
State 2
Resetting States...
This will always also be printed no matter what happens
This will always be printed no matter what happens.
State 1
State 2
Resetting States...
This will always also be printed no matter what happens
Aaand repeat. Plus, if we extend this to have more than two variables and possible values, it should be able to hold up, even at the expanse of CPU speed, since we're just essentially breaking out of a block.