Lesson 19 +10 XP

C# Switch

C# Switch

The switch statement selects one of many code blocks to run.

The switch statement

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;
  default:
    Console.WriteLine("Looking forward to the Weekend");
    break;
}

This prints Thursday because day equals 4.

How it works

  • The value of the switch expression is tested against each case.
  • C# checks the cases from top to bottom.
  • Each case must end with a break; (or return, goto, etc.).
  • default runs if no case matches.

No fall-through

Unlike C, C# does not allow falling through from one case into the next. Every case needs its own ending like break;.

Switch with strings

switch works with strings too:

string color = "red";
switch (color)
{
  case "red":
    Console.WriteLine("Stop");
    break;
  default:
    Console.WriteLine("Go");
    break;
}

TL;DR

  • switch picks one of many cases based on a value.
  • default runs when nothing matches.
  • Every case needs break; - no fall-through.
  • Works with numbers and strings.