C# - TPL2141 logo C# - TPL2141

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:

  1. A bool literal
    1. true, or
    2. false
  2. Any integral constant
    1. int
    2. long
    3. byte
    4. etc
  3. The name of a declared const variable.
  4. An enumeration constant.
    1. DayOfWeek.Sunday
  5. A char literal.
  6. 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:

  1. break
  2. goto case
  3. goto label
  4. return
  5. 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

  1. Docs, M. (Ed.). (2018, August 14). switch (C# reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch