C# Switch Statements

Use the switch statement to select one of the many code blocks to be used.

Syntax
switch(expression) 
            {
              case x:
                // code block
                break;
              case y:
                // code block
                break;
              default:
                // code block
                break;
            }
            

This is how it works:

  • The switch expression is evaluated once
  • The value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed
  • The break and default keywords will be described later in this chapter

The example below uses the number of days of the week to calculate the name of the day of the week:

Example
int day = 4;
            switch (day) 
            {
              case 1:
                Console.WriteLine("Monday");
                break;
              case 2:
                Console.WriteLine("Tuesday");
                break;
              case 3:
                Console.WriteLine("Wednesday");
                break;
              case 4:
                Console.WriteLine("Thursday");
                break;
              case 5:
                Console.WriteLine("Friday");
                break;
              case 6:
                Console.WriteLine("Saturday");
                break;
              case 7:
                Console.WriteLine("Sunday");
                break;
            }
            // Outputs "Thursday" (day 4)
            

The break Keyword

When C# reaches the break keyword, it exits the switch block.

This will stop additional code creation and case testing within the block.

Once the game is over, and the job is over, it’s break time. No further testing is required.

The default Keyword

The default keyword is optional and specifies a specific code to apply in case of no match:

Example
int day = 4;
            switch (day) 
            {
              case 6:
                Console.WriteLine("Today is Saturday.");
                break;
              case 7:
                Console.WriteLine("Today is Sunday.");
                break;
              default:
                Console.WriteLine("Looking forward to the Weekend.");
                break;
            }
            // Outputs "Looking forward to the Weekend."