C# Switch
The switch statement is an alternative to long if/else if chains when comparing one variable against many possible values. Each case represents a possible match, and break stops execution from falling into the next case.
Modern C# also supports switch expressions, a more concise syntax that directly returns a value based on the matched case.
switch (value) {
case 1:
// code
break;
default:
// code
break;
}switch statement
A switch statement compares a value against several case labels. When a match is found, the corresponding code runs, and break exits the switch. default handles any unmatched value.
switch expressions
Switch expressions use `=>` to map cases directly to values, avoiding repetitive break statements and making pattern matching more concise.
using System;
class Program {
static void Main() {
int day = 3;
switch (day) {
case 1:
Console.WriteLine("Monday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Other day");
break;
}
}
}Wednesdayday matches case 3, so 'Wednesday' is printed and break exits the switch.
using System;
class Program {
static void Main() {
int day = 6;
string name = day switch {
1 => "Monday",
6 => "Saturday",
_ => "Unknown"
};
Console.WriteLine(name);
}
}SaturdayThe switch expression maps day 6 directly to the string 'Saturday'.
Key points
- switch compares one value against multiple case labels.
- break prevents execution from falling into the next case.
- default handles any value that doesn't match a case.
- Switch expressions (=>) offer a more concise alternative syntax.
