candland

@candland rss self
February 14th 2007

Switch statement and the goto command.

The goto command can be used to within a switch statement to transfer control to other case statements or the default case statement. Using goto case <constant value> will transfer control to that case statement. Using goto default will transfer execute to the default statement. I’m not sure it produces the cleanest code, but here’s an example anyway.

public void SwitchMe(StatesEnum state) 
{
switch (state)
{
case StatesEnum.Stopped:
Start();
goto case StatesEnum.Starting;
case StatesEnum.Started:
Stop();
goto case StatesEnum.Stopping;
case StatesEnum.Stopping:
state = StatesEnum.Stopping;
goto default;
case StatesEnum.Starting:
state = StatesEnum.Starting;
goto default;
default:
Log(state);
break;
}
}

public enum StatesEnum
{
Stopped,
Starting,
Started,
Stopping
}

So, looking above, if state = Stopped and was passed to the SwitchMe method, the code would execute as follows:

  1. the Stopped case would execute calling the Start method
  2. the Starting case would execute setting the value of state to Starting
  3. the default case would execute calling the Log method

blog comments powered by Disqus