Switch là selection statement chọn single switch section để execute từ list candidates dựa trên pattern match với match expression.
Switch statement thường dùng như alternative cho if-else construct nếu single expression được test chống lại three hoặc more conditions.
Switch statement nhanh hơn. Với switch statement, average number of comparisons sẽ là one bất kể có bao nhiêu cases khác nhau. So lookup của arbitrary case là O(1).
Dùng Switch
class Program {
public enum Fruits { Red, Green, Blue }
public static void Main() {
Fruits c = (Fruits)(new Random()).Next(0, 3);
switch (c) {
case Fruits.Red:
Console.WriteLine("The Fruits is red");
break;
case Fruits.Green:
Console.WriteLine("The Fruits is green");
break;
case Fruits.Blue:
Console.WriteLine("The Fruits is blue");
break;
default:
Console.WriteLine("The Fruits is unknown.");
break;
}
Console.ReadLine();
}
}
Dùng If Else
class Program {
public enum Fruits { Red, Green, Blue }
public static void Main() {
Fruits c = (Fruits)(new Random()).Next(0, 3);
if (c == Fruits.Red)
Console.WriteLine("The Fruits is red");
else if (c == Fruits.Green)
Console.WriteLine("The Fruits is green");
else if (c == Fruits.Blue)
Console.WriteLine("The Fruits is blue");
else
Console.WriteLine("The Fruits is unknown.");
Console.ReadLine();
}
}
So sánh Chi Tiết
| Đặc điểm | if/else if/else | switch (Statement) | switch (Expression C# 8+) |
|---|---|---|---|
| Performance | O(n) - kiểm tra tuần tự | O(1) - jump table (n ≥ ~5) | O(1) - pattern matching |
| Readability | Tốt cho 2-3 conditions | Tốt cho nhiều discrete values | Tốt nhất - expression-based |
| Type Support | Mọi type (bool, string, object) | Integral, enum, string, nullable | Mọi type (pattern matching) |
| Complex Conditions | ✅ (x > 5 && y < 10) | ❌ Chỉ equality/constant | ✅ Property, relational, logical patterns |
| Range Checks | ✅ Dễ dàng | ❌ Khó (cần multiple cases) | ✅ Relational patterns (C# 9+) |
| Returns Value | Không trực tiếp | Không | ✅ Expression-bodied |
| Fall-through | Không | Có (cần break) | Không |
Khi nào dùng cái nào?
Dùng if/else khi:
- 2-3 conditions đơn giản
- Cần complex boolean expressions (&&, ||, !)
- Range checks:
if (age >= 18 && age < 65) - Null checks:
if (obj != null && obj.IsValid) - Type checks với pattern matching:
if (obj is string s && s.Length > 0)
Dùng Switch Statement khi:
- So sánh single variable với multiple constant values
- Enum values (exhaustiveness checking)
- String literals (culture-sensitive comparison)
- Cần fall-through behavior (hiếm)
Dùng Switch Expression (C# 8+) khi:
- Cần return value
- Pattern matching phức tạp (type, property, tuple)
- Expression-bodied members
- LINQ queries
- Exhaustiveness checking quan trọng
Performance Deep Dive
Switch Statement - Jump Table
// Compiler tạo jump table cho dense integer/enum switches
switch (value) {
case 1: ... break;
case 2: ... break;
case 100: ... break; // Sparse - có thể dùng binary search
}
// IL: switch opcode → jump table
String Switch - Hashtable
switch (str) {
case "A": ... break;
case "B": ... break;
}
// Compiler tạo Dictionary mapping string → case index
Modern C#: Pattern Matching Everything
// C# 9+ - Pattern matching trong if
if (shape is Rectangle { Width: > 0, Height: > 0 } rect) {
area = rect.Width * rect.Height;
}
else if (shape is Circle { Radius: > 0 } circle) {
area = Math.PI * circle.Radius * circle.Radius;
}
// C# 11+ - List patterns
if (numbers is [1, 2, .., 9, 10]) {
// Starts with 1,2 and ends with 9,10
}