C# switch

Summary: in this tutorial, you’ll learn how to use the C# switch statement to select a block for execution if an expression matches a pattern.

Introduction to the C# switch statement

The switch statement evaluates an expression and selects a block for execution if the expression satisfies a condition. The syntax of the switch statement is as follows:

switch (expression)
{
    case label1:
        // block1;
        break;
    case label2:
        // block2;
        break;
    case label3:
        // block3;
        break;
    default:
        // blockn;
        break;
}Code language: C# (cs)

In this syntax, the switch statement matches the expression with label1, label2, label3, … in each case clause from top to bottom.

If the expression matches a label, the switch statement will execute the corresponding block and pass the control to the following statement.

If the expression doesn’t match any label, the switch statement executes the block in the default clause.

The default clause is optional. If you don’t specify it and the expression doesn’t match any label, the switch statement doesn’t execute any block and passes the control to the statement after it.

The switch statement uses many patterns to match the expression with the labels. In this tutorial, you’ll focus on the following patterns:

  • A constant pattern: test if the result of the expresion is equal to a constant.
  • A relational pattern: compare the result of the expression with a constant using a relational operator such as <, <=, >, >=.

The following flowchart illustrates how the switch statement works.

c# switch

C# switch statement example

The following program uses the switch statement to display the month name based on the month number entered by users:

Console.Write("Enter a month(1-12): ");
int month = Convert.ToInt32(Console.ReadLine());

string name;

switch (month)
{
    case 1:
        name = "Jan";
        break;
    case 2:
        name = "Feb";
        break;
    case 3:
        name = "Mar";
        break;
    case 4:
        name = "Apr";
        break;
    case 5:
        name = "May";
        break;
    case 6:
        name = "Jun";
        break;
    case 7:
        name = "Jul";
        break;
    case 8:
        name = "Aug";
        break;
    case 9:
        name = "Sep";
        break;
    case 10:
        name = "Nov";
        break;
    case 11:
        name = "Dec";
        break;
    case 12:
        name = "Aug";
        break;
    default:
        name = "Invalid month";
        break;
}


Console.WriteLine(name);Code language: C# (cs)

How it works.

First, prompt users to input a number from 1 to 12:

Console.Write("Enter a month(1-12): ");
int month = Convert.ToInt32(Console.ReadLine());Code language: C# (cs)

Second, match the input month number with a number from 1 to 12 using the switch statement and assign the month name accordingly.

If the month number is not in the range of 1 to 12, the month name will be “Invalid month”:

string name;

switch (month)
{
    case 1:
        name = "Jan";
        break;
    case 2:
        name = "Feb";
        break;
    case 3:
        name = "Mar";
        break;
    case 4:
        name = "Apr";
        break;
    case 5:
        name = "May";
        break;
    case 6:
        name = "Jun";
        break;
    case 7:
        name = "Jul";
        break;
    case 8:
        name = "Aug";
        break;
    case 9:
        name = "Sep";
        break;
    case 10:
        name = "Nov";
        break;
    case 11:
        name = "Dec";
        break;
    case 12:
        name = "Aug";
        break;
    default:
        name = "Invalid month";
        break;
}Code language: C# (cs)

Third, display the month name:

Console.WriteLine(name);Code language: C# (cs)

Group case in the C# switch statement

If you have the same block that corresponds to multiple cases, you can group cases in the switch statement like this:

switch (expression)
{

    case firstCase:
    case secondCase:
        // block 1
        break;

    case thirdCase:
    case fourthCase:
        // block 2
        break;
    default:
        // block n
        break;

}Code language: C# (cs)

In this syntax, the switch statement will execute block 1 if the expression matches the firstCase and secondCase. Likewise, it’ll execute block 2 if the expression matches the thirdCase and fourthCase.

If the expression doesn’t match any labels in the case clauses, it’ll execute the block n in the default clause.

The following example prompts users to input a month number and display the corresponding quarter name of that month:

Console.Write("Enter a month(1-12): ");
int month = Convert.ToInt32(Console.ReadLine());

string quarter;

switch (month)
{
    case 1:
    case 2:
    case 3:
        quarter = "Q1";
        break;
    case 4:
    case 5:
    case 6:
        quarter = "Q2";
        break;
    case 7:
    case 8:
    case 9:
        quarter = "Q3";
        break;
    case 10:
    case 11:
    case 12:
        quarter = "Q4";
        break;

    default:
        quarter = "Invalid quarter";
        break;
}

Console.WriteLine(quarter);Code language: C# (cs)

How it works.

First, prompt users to input a month number from 1 to 12:

Console.Write("Enter a month(1-12): ");
int month = Convert.ToInt32(Console.ReadLine());Code language: C# (cs)

Second, set the quarter based on the month number using the switch statement with group cases:

string quarter;

switch (month)
{
    case 1:
    case 2:
    case 3:
        quarter = "Q1";
        break;
    case 4:
    case 5:
    case 6:
        quarter = "Q2";
        break;
    case 7:
    case 8:
    case 9:
        quarter = "Q3";
        break;
    case 10:
    case 11:
    case 12:
        quarter = "Q4";
        break;

    default:
        quarter = "Invalid quarter";
        break;
}Code language: C# (cs)

Third, display the quarter name:

Console.WriteLine(quarter);Code language: C# (cs)

C# switch statement with relation pattern example

Starting in C# 9, you can use use the relational operator >, >=, <, <= to match the result of the expression with constants in the switch statement.

We’ll rewrite the body mass index (BMI) calculation program in the if else if statement tutorial using the switch statement with the relational pattern:

Console.WriteLine("Body Mass Index (BMI) Calculation");

Console.WriteLine("Enter a weight (kg):");
var weight = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter a height (m):");
var height = Convert.ToDouble(Console.ReadLine());


double bmi = weight / (height * height);
string weightStatus = "";

switch (bmi)
{
    case < 18.5:
        weightStatus = "Underweight";
        break;
    case >= 18.5 and <= 24.9:
        weightStatus = "Healthy Weight";
        break;
    case >= 25 and <= 29.9:
        weightStatus = "Overweight";
        break;
    case > 30:
        weightStatus = "Obesity";
        break;
}


Console.WriteLine($"BMI: {bmi:0.#}");
Console.WriteLine($"Weight status:{ weightStatus}");Code language: C# (cs)

How it works.

First, prompt users to enter their weight in kg and height in m:

Console.WriteLine("Body Mass Index (BMI) Calculation");

Console.WriteLine("Enter a weight (kg):");
var weight = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter a height (m):");
var height = Convert.ToDouble(Console.ReadLine());Code language: C# (cs)

Second, calculate the BMI by taking the weight divided by the square of height:

double bmi = weight / (height * height);Code language: C# (cs)

Third, assign the weight status based on the BMI value:

string weightStatus = "";

switch (bmi)
{
    case < 18.5:
        weightStatus = "Underweight";
        break;
    case >= 18.5 and <= 24.9:
        weightStatus = "Healthy Weight";
        break;
    case >= 25 and <= 29.9:
        weightStatus = "Overweight";
        break;
    case > 30:
        weightStatus = "Obesity";
        break;
}Code language: C# (cs)

Finally, display the BMI and weight status:

Console.WriteLine($"BMI: {bmi:0.#}");
Console.WriteLine($"Weight status:{ weightStatus}");Code language: C# (cs)

As you can see, the switch statement is much more readable than the if else if statement.

Summary

  • Use the switch statement to execute a block if an expression matches a pattern.
  • The switch statement uses many matching patterns.
  • Use the constant pattern to test if the expression result is equal to a constant.
  • Use the relational pattern to test the expression result with a constant using the relational operator <, <=, >, >=.
  • Use a group case to execute the same block that corresponds to multiple cases.
  • The switch statement executes the block in the default clause if the expression doesn’t match any cases. The default clause is optional.
Was this tutorial helpful ?