Profile picture Schedule a Meeting
c a n d l a n d . n e t

Switch statement and the goto command.

Dusty Candland | |

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 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

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: