C# Switch

C# Switch Statements

Instead of writing many if...else if statements to check the exact same variable against different values, you can use the switch statement. It is cleaner, faster, and easier to read.


The Switch Syntax

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.

Switch Example

using System;

class Program { static void Main() { 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"); // This matches and runs break; case 5: Console.WriteLine("Friday"); break; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; } } }


The break Keyword

When C# reaches a break keyword, it immediately exits out of the switch block. This prevents the code from executing the remaining cases, which saves execution time. Every case must end with a break (or a return), otherwise, the C# compiler will throw an error.

The default Keyword

The default keyword specifies some code to run if there is no match in any of the cases. It acts similarly to the else statement at the end of an if...else chain.

int day = 8;
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."); // This will run
    break;
}

Exercise

?

Which keyword stops the execution of more cases inside a switch?