Điều kiện
Ghi nhớ nhanh
Phần tiêu đề “Ghi nhớ nhanh”Dùng điều kiện để chọn nhánh chạy code.
switch expression gọn khi cần trả về một giá trị theo nhiều trường hợp.
Cú pháp
Phần tiêu đề “Cú pháp”if (score >= 9){ Console.WriteLine("Excellent");}else if (score >= 7){ Console.WriteLine("Good");}else{ Console.WriteLine("Try again");}Ví dụ
Phần tiêu đề “Ví dụ”switch
Phần tiêu đề “switch”string role = "admin";
switch (role){ case "admin": Console.WriteLine("Full access"); break; case "user": Console.WriteLine("Limited access"); break; default: Console.WriteLine("Guest"); break;}Switch expression
Phần tiêu đề “Switch expression”int score = 8;
string rank = score switch{ >= 9 => "Excellent", >= 7 => "Good", >= 5 => "Average", _ => "Fail"};Pattern matching cơ bản
Phần tiêu đề “Pattern matching cơ bản”object value = "hello";
if (value is string text){ Console.WriteLine(text.ToUpper());}Pattern matching thường gặp
Phần tiêu đề “Pattern matching thường gặp”| Pattern | Dùng khi | Ví dụ |
|---|---|---|
| Type pattern | Kiểm tra kiểu | value is string s |
| Constant pattern | So với hằng | status is 404 |
| Relational pattern | So sánh | score is >= 8 |
| Logical pattern | Kết hợp điều kiện | age is >= 18 and < 60 |
| Property pattern | Kiểm tra property | user is { IsActive: true } |
| Null pattern | Kiểm tra null | value is null |
string label = user switch{ { IsActive: true, Role: "Admin" } => "Admin active", { IsActive: true } => "User active", null => "Missing", _ => "Inactive"};Chọn if hay switch
Phần tiêu đề “Chọn if hay switch”| Tình huống | Nên dùng |
|---|---|
| 1-2 điều kiện đơn giản | if |
| Nhiều nhánh theo cùng một biến | switch |
| Cần trả về giá trị gọn | switch expression |
| Điều kiện phức tạp, cần log/debug | if rõ ràng hơn |
Lỗi thường gặp
Phần tiêu đề “Lỗi thường gặp”- Quên
breaktrongswitchkiểu statement. - Viết điều kiện quá dài; nên tách biến boolean có tên rõ.
- Dùng
_trong switch expression trước các case cụ thể. - Quên xử lý
nullkhi dùng property pattern. - Lồng quá nhiều
if; cân nhắc guard clause.
Tham khảo chính thức
Phần tiêu đề “Tham khảo chính thức”Từ khóa tìm kiếm
Phần tiêu đề “Từ khóa tìm kiếm”if, else, else if, condition, điều kiện, switch, switch expression, pattern matching, is, property pattern, relational pattern, guard clause