Switch - Case
This is a control statement that chooses a section block from a list of possible choices.
You typically use a break statement to terminate a switch section block
You can throw and return to exit a block
A switch statement includes one or more switch section blocks.
A switch contains one or more case labels, followed by one or more statements
If no match is found, control is transferred to the default section block (if there is one)
If there is no match and no default section then no action is taken
Execution continues in the section until a jump statement is reached: break; goto case; return; throw
switch (Temp)
{
case 0:
r += 1;
break;
case "green"
r++;
break;
case "blue" : break;
case "red": case "yellow": case "purple":
break;
case "pink"
case "violet"
case "black"
default:
break; //you must always have a break out from a case
}
Select Case Temp
Case "red"
r += 1
Case "green"
r = r + 1
Case "blue"
Case Else : 'same line
End Select
Fall Through Cases
The following fall through case is supported
int x = 1;
switch (x)
{
case 0:
case 1:
default:
{
System.Console.Writeline(x);
break;
}
}
Goto Transfers
The goto keyword can be used for explicit transfers
int x = 0;
switch (x)
{
case 0 :
goto case 1
case 1 :
{
System.Console.WriteLine("1");
goto default;
{
default:
{
break;
}
}
Important
Unlike C++, control cannot continue from one switch to the next.
© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext