Loading lessons...
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
switchexpression is tested against eachcase. - C# checks the cases from top to bottom.
- Each
casemust end with abreak;(orreturn,goto, etc.). defaultruns 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
switchpicks one of many cases based on a value.defaultruns when nothing matches.- Every case needs
break;- no fall-through. - Works with numbers and strings.