Bỏ qua để đến nội dung

Điều kiện

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.

if (score >= 9)
{
Console.WriteLine("Excellent");
}
else if (score >= 7)
{
Console.WriteLine("Good");
}
else
{
Console.WriteLine("Try again");
}
string role = "admin";
switch (role)
{
case "admin":
Console.WriteLine("Full access");
break;
case "user":
Console.WriteLine("Limited access");
break;
default:
Console.WriteLine("Guest");
break;
}
int score = 8;
string rank = score switch
{
>= 9 => "Excellent",
>= 7 => "Good",
>= 5 => "Average",
_ => "Fail"
};
object value = "hello";
if (value is string text)
{
Console.WriteLine(text.ToUpper());
}
PatternDùng khiVí dụ
Type patternKiểm tra kiểuvalue is string s
Constant patternSo với hằngstatus is 404
Relational patternSo sánhscore is >= 8
Logical patternKết hợp điều kiệnage is >= 18 and < 60
Property patternKiểm tra propertyuser is { IsActive: true }
Null patternKiểm tra nullvalue is null
string label = user switch
{
{ IsActive: true, Role: "Admin" } => "Admin active",
{ IsActive: true } => "User active",
null => "Missing",
_ => "Inactive"
};
Tình huốngNên dùng
1-2 điều kiện đơn giảnif
Nhiều nhánh theo cùng một biếnswitch
Cần trả về giá trị gọnswitch expression
Điều kiện phức tạp, cần log/debugif rõ ràng hơn
  • Quên break trong switch kiể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ý null khi dùng property pattern.
  • Lồng quá nhiều if; cân nhắc guard clause.

if, else, else if, condition, điều kiện, switch, switch expression, pattern matching, is, property pattern, relational pattern, guard clause