When you're checking a single value against a bunch of possible matches, a long if-else if chain gets noisy. Enter switch โ cleaner, more readable, and built exactly for this job.
Basic switch
You hand switch a value. It jumps to the case that matches. Each case needs a break to stop it from falling through to the next.
using System;
class Program {
static void Main() {
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;
}
}
}
Try it Yourself โ
Pattern Matching with switch
C# modernized switch with pattern matching. You can match types, ranges, and even add conditions with when.
using System;
class Program {
static void Main() {
object value = 42;
switch (value) {
case int i when i > 0:
Console.WriteLine("Positive integer: " + i);
break;
case string s:
Console.WriteLine("String: " + s);
break;
case null:
Console.WriteLine("It's null");
break;
default:
Console.WriteLine("Something else");
break;
}
}
}
Try it Yourself โ
fall-through Behavior
Unlike C or C++, C# requires a break (or return, goto) at the end of each case. Accidental fall-through is a compile error โ the compiler has your back.
using System;
class Program {
static void Main() {
char grade = 'B';
switch (grade) {
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Good effort");
break;
case 'D':
Console.WriteLine("Needs improvement");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
}
}
Try it Yourself โ
switch Expression
C# 8.0 introduced switch expressions โ a compact, functional style that returns a value directly without all the case/break ceremony.
using System;
class Program {
static void Main() {
int day = 3;
string name = day switch {
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
_ => "Weekend"
};
Console.WriteLine(name);
}
}
Try it Yourself โ