Switch เป็น Selection Statement ที่เลือก Switch Section เดียวจาก List ของ Candidates ตาม Pattern Match กับ Match Expression
Switch Statement บ่อยครั้งใช้แทน If-Else Construct ถ้า Single Expression ถูก Test กับ 3+ Conditions
Switch Statement เร็วกว่า ใน Switch Statement จำนวนการ Compare เฉลี่ยจะเป็น 1 ไม่ว่าจะมี Cases กี่ตัว Lookup ของ Arbitrary Case เป็น O(1)
ใช้ Switch Statement
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 fruit is red");
break;
case Fruits.Green:
Console.WriteLine("The fruit is green");
break;
case Fruits.Blue:
Console.WriteLine("The fruit is blue");
break;
default:
Console.WriteLine("The fruit is unknown.");
break;
}
Console.ReadLine();
}
}
ใช้ 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 fruit is red");
else if (c == Fruits.Green)
Console.WriteLine("The fruit is green");
else if (c == Fruits.Blue)
Console.WriteLine("The fruit is blue");
else
Console.WriteLine("The fruit is unknown.");
Console.ReadLine();
}
}
ความแตกต่างสำคัญ
| Aspect | if/else | switch |
|---|---|---|
| Performance (Many Cases) | O(n) - Linear Search | O(1) - Jump Table/Hash |
| Readability (3+ Conditions) | ยุ่งยาก | ชัดเจน, Structured |
| Fall-through | ไม่ได้ (ต้อง Duplicate Code) | ได้ (C# ไม่ Allow Fall-through โดย Default) |
| Pattern Matching | Limited | Full (C# 7+) |
| Range Checks | เหมาะสม (x > 0 && x < 10) | ไม่ได้ (C# 7), ได้ (C# 9+ Relational) |
| Complex Expressions | ได้ (Method Calls, &&, ||) | Constant Patterns เท่านั้น (C# 7), Patterns (C# 8+) |
| String Comparison | ได้ (Ordinal, Culture) | Ordinal เท่านั้น (Case-sensitive) |
เมื่อไหร่ควรใช้ Switch
- Compare Single Variable/Expression กับ Multiple Constant Values
- Enum Values (Exhaustiveness Checking)
- Pattern Matching (Type, Property, Tuple Patterns)
- 3+ Discrete Values
- Performance Critical (Hot Path)
เมื่อไหร่ควรใช้ If/Else
- Range/Relational Checks (
x > 0 && x < 100) - Complex Boolean Expressions (
a > 0 || b < 10) - Non-constant Comparisons (
x == GetValue()) - String Comparison ที่ต้องการ Culture/Ordinal Options
- 2 Conditions เท่านั้น (If/Else เรียบง่ายกว่า)
Modern C#: Switch Expressions (C# 8.0+)
// Expression-bodied, Returns Value
var message = fruit switch {
"Apple" => "Red",
"Banana" => "Yellow",
"Orange" => "Orange",
_ => "Unknown"
};
// Pattern Matching
var description = shape switch {
Circle c => $"Circle r={c.Radius}",
Rectangle r => $"Rect {r.Width}x{r.Height}",
Triangle t => $"Triangle",
null => "None",
_ => "Unknown"
};
Benchmark (Reference)
// 10 Cases, 1M Iterations
// if/else: ~45ms
// switch: ~12ms
// switch expression: ~10ms
Note: ใน C# Modern Compiler มัก Optimize If/Else ให้เป็น Jump Table เหมือน Switch เมื่อ Detect Pattern ที่เหมาะสม