switch is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression (Docs, 2018)
int caseSwitch = 2;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
case 4:
Console.WriteLine($"Case {caseSwitch}");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine($"Unexpcted value ({caseSwitch})");
break;
}
Output:
Case 2
Live-code example
The general syntax for each case label is
case constant:
where constant can be any of the following expressions:
- A
bool
literaltrue
, orfalse
- Any integral constant
int
long
byte
- etc
- The name of a declared
const
variable. - An enumeration constant.
DayOfWeek.Sunday
- A
char
literal. - A
string
literal.
The switch statement provides a clean alternative for writing multiple if-else statements. The example above can be written as:
int caseSwitch = 1;
if (caseSwitch == 1)
{
Console.WriteLine("Case 1");
}
else if (caseSwitch == 2 || caseSwitch == 4)
{
Console.WriteLine($"Case {caseSwitch}");
}
else if (caseSwitch == 3)
{
Console.WriteLine("Case 3");
}
else
{
Console.WriteLine($"Unexpcted value ({caseSwitch})");
}
Live-code example
Multiple case labels
As you might have noticed in the previous switch example, a switch section can have multiple case labels
case 2:
case 4:
Console.WriteLine($"Case {caseSwitch}");
However in that case, C# does not allow execution to continue from one switch section to the next. The code below will generate a compiler error:
CS0163: “Control cannot fall through from one case label () to another.”
int caseSwitch = 1;
switch (caseSwitch)
{
// The following switch section causes an error.
case 1:
Console.WriteLine("Case 1...");
// a jump statement is needed here
case 2:
Console.WriteLine("... and/or Case 2");
break;
}
Live-code example
Jump statements include:
- break
- goto case
- goto label
- return
- throw
default case
The default
case, which is optional, specifies what to execute if the match expression does not match with any of the case labels. This is similar to the last else
clause in the if-elseif-else example.
References
- Docs, M. (Ed.). (2018, August 14). switch (C# reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch