Classic switch Statement
The switch statement compares a variable against a list of case labels. Each case ends with break (unlike C++, fall-through requires an explicit goto case). The optional default case handles any unmatched value.
Classic switch
Switch.cs
int day = 3;
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;
default: Console.WriteLine("Weekend"); break;
}Switch Expression (C# 8+)
The switch expression returns a value and uses arrow (=>) syntax. It is more concise and works well with pattern matching. Every possible input must be handled—the compiler warns you if a case is missing.
Switch expression
SwitchExpr.cs
int day = 3;
string name = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 or 7 => "Weekend",
_ => throw new ArgumentOutOfRangeException()
};
Console.WriteLine(name); // WednesdayPattern Matching in switch
Switch expressions shine with type and relational patterns, allowing complex branching logic in a readable table-like format.
Pattern switch
PatternSwitch.cs
static string Classify(object obj) => obj switch
{
int n when n < 0 => "Negative integer",
int n when n == 0 => "Zero",
int => "Positive integer",
string s => $"String of length {s.Length}",
null => "Null",
_ => "Unknown type"
};
Console.WriteLine(Classify(-5)); // Negative integer
Console.WriteLine(Classify("Hi")); // String of length 2