Control Flow
Định nghĩa (Definition)
Luồng điều khiển (Control Flow) đề cập đến thứ tự thực thi các câu lệnh, hướng dẫn hoặc lời gọi hàm riêng lẻ trong một chương trình. C# cung cấp câu lệnh điều kiện (Conditional Statements) (if, switch) để rẽ nhánh, vòng lặp (Loops) (for, foreach, while, do-while) để lặp lại, và câu lệnh nhảy (Jump Statements) (break, continue, return) để chuyển điều khiển.
Các khái niệm cốt lõi (Core Concepts)
if / else if / else
Câu lệnh if đánh giá một biểu thức Boolean (Boolean Expression) và thực thi một khối lệnh có điều kiện.
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
// Output: Grade: B
Khi thân chỉ có một câu lệnh, dấu ngoặc nhọn về mặt kỹ thuật là tùy chọn nhưng luôn sử dụng dấu ngoặc nhọn để dễ đọc và ngăn ngừa lỗi khi thêm dòng sau này.
Câu lệnh switch (Switch Statement)
Câu lệnh switch chọn một đoạn để thực thi từ danh sách các trư ờng hợp dựa trên khớp mẫu (Pattern Match).
Switch truyền thống:
string dayOfWeek = DateTime.Now.DayOfWeek.ToString();
switch (dayOfWeek)
{
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
Console.WriteLine("Weekday");
break; // C# requires explicit break
case "Saturday":
case "Sunday":
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Unknown");
break;
}
Switch với khớp mẫu (Pattern Matching) (C# 7+):
object value = 42;
switch (value)
{
case int i when i > 0:
Console.WriteLine($"Positive integer: {i}");
break;
case string s:
Console.WriteLine($"String of length {s.Length}");
break;
case null:
Console.WriteLine("Null value");
break;
default:
Console.WriteLine("Something else");
break;
}
Biểu th ức switch (Switch Expressions) (C# 8+)
Biểu thức switch (Switch Expressions) ngắn gọn hơn và trả về một giá trị. Chúng sử dụng khớp mẫu (Pattern Matching) với cú pháp mũi tên =>.
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F" // _ is the discard pattern (default)
};
Với mẫu tuple (Tuple Patterns):
string Classify(int x, int y) => (x, y) switch
{
(0, 0) => "Origin",
(> 0, > 0) => "Quadrant I",
(< 0, > 0) => "Quadrant II",
(< 0, < 0) => "Quadrant III",
(> 0, < 0) => "Quadrant IV",
(0, _) or (_, 0) => "On an axis"
};
Biểu thức switch (Switch Expressions) ngắn gọn hơn, hướng biểu thức (Expression-Oriented) và ít lỗi hơn câu lệnh switch (Switch Statements). Sử dụng chúng khi cần tạo giá trị từ rẽ nhánh nhiều hướng.