Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Decision Making (การตัดสินใจ) ใน C#: if, else, switch

Decision Making Structures ใน C# ใช้ควบคุมการไหลของโปรแกรมตามเงื่อนไข ประกอบด้วย if, if-else, switch, ternary operator

if Statement

int x = 5;
if (x < 20)
{
    Console.WriteLine("x น้อยกว่า 20");
}
Console.WriteLine($"ค่า x = {x}");

if-else Statement

int x = 100;
if (x < 20)
{
    Console.WriteLine("x น้อยกว่า 20");
}
else
{
    Console.WriteLine("x ไม่น้อยกว่า 20");
}
Console.WriteLine($"ค่า x = {x}");

if-else if-else Ladder

int score = 85;
if (score >= 90) Console.WriteLine("A");
else if (score >= 80) Console.WriteLine("B");
else if (score >= 70) Console.WriteLine("C");
else if (score >= 60) Console.WriteLine("D");
else Console.WriteLine("F");

Switch Statement (Classic)

int day = 3;
switch (day)
{
    case 1: Console.WriteLine("Monday"); break;
    case 2: Console.WriteLine("Tuesday"); break;
    case 3: Console.WriteLine("Wednesday"); break;
    default: Console.WriteLine("Other day"); break;
}

Switch Expression (C# 8+) - แนะนำ

string dayName = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    _ => "Other day" // default
};

Pattern Matching Switch (C# 7+)

object obj = "Hello";
string result = obj switch
{
    int i => $"Integer: {i}",
    string s when s.Length > 5 => $"Long string: {s}",
    string s => $"Short string: {s}",
    null => "Null",
    _ => "Unknown"
};

Ternary Operator (?:)

int x = 10;
string msg = x > 0 ? "Positive" : "Non-positive";
// เทียบเท่า
string msg2;
if (x > 0) msg2 = "Positive"; else msg2 = "Non-positive";

Best Practices

  • ใช้ switch expression แทน Statement สำหรับ Return Value
  • Pattern Matching เพื่อ Type Checking + Condition รวมกัน
  • หลีกเลี่ยง Nested If ลึกเกินไป (Extract Method / Guard Clauses)
  • ใช้ ?. และ ?? สำหรับ Null Checking แทน If ตรวจสอบ Null