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

Ternary Operator ใน C# - Conditional Operator

Ternary Operator (ออปเปอเรเตอร์ทวิภาค) หรือ Conditional Operator ใน C# เป็นออปเปอเรเตอร์ที่รับอาร์กิวเมนต์ 3 ตัว และประเมินค่าสมการ Boolean เป็นวิธีเขียนเงื่อนไข if-else แบบย่อให้กระชับ

Syntax

condition ? expression_if_true : expression_if_false;

ตัวอย่างพื้นฐาน

int a = 10;
int b = (a == 1) ? 20 : 30;  // a ไม่เท่ากับ 1 ดังนั้น b = 30

Console.WriteLine(b);  // Output: 30

b = (a == 10) ? 20 : 30; // a เท่ากับ 10 ดังนั้น b = 20
Console.WriteLine(b);  // Output: 20

ตัวอย่างโค้ดสมบูรณ์

using System;

namespace DEMO {
    class Program {
        static void Main(string[] args) {
            int a, b;
            a = 10;
            
            // ถ้า a == 1 ให้ b = 20 มิฉะนั้น b = 30
            b = (a == 1) ? 20 : 30;
            Console.WriteLine("Value of b is {0}", b);  // 30
            
            // ถ้า a == 10 ให้ b = 20 มิฉะนั้น b = 30
            b = (a == 10) ? 20 : 30;
            Console.WriteLine("Value of b is {0}", b);  // 20
            
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Value of b is 30
Value of b is 20

การใช้งานขั้นสูง

1. Nested Ternary (ซ้อนกัน) - ใช้เพื่อหลายเงื่อนไข

int score = 85;
string grade = score >= 90 ? "A" :
               score >= 80 ? "B" :
               score >= 70 ? "C" :
               score >= 60 ? "D" : "F";

Console.WriteLine(grade);  // B

2. กับ Null Coalescing (??) ร่วมกัน

string name = null;
string displayName = name ?? "Guest";  // ถ้า null ให้ "Guest"

// เทียบเท่า:
string displayName2 = name != null ? name : "Guest";

3. ใน Expression-bodied Members

public string GetStatus(bool isActive) => isActive ? "Active" : "Inactive";
public int Max(int a, int b) => a > b ? a : b;

4. ใช้ใน LINQ / Lambda

var numbers = new[] { 1, 2, 3, 4, 5, 6 };
var result = numbers.Select(n => n % 2 == 0 ? "Even" : "Odd");
// Result: Odd, Even, Odd, Even, Odd, Even

ข้อควรระวัง

  • Readability - ไม่ควรซ้อนเกิน 2-3 ระดับ จะอ่านยาก
  • Type Compatibility - ทั้งสอง branch ต้องมีชนิดข้อมูลเดียวกันหรือสามารถแปลงได้
  • Side Effects - หลีกเลี่ยงการเรียกเมธอดที่มี side effect ภายใน ternary

เทียบกับ if-else

ด้าน Ternary Operator if-else Statement
เป็น Expression ใช่ (คืนค่าได้) ไม่ (เป็น Statement)
ความกระชับ สูง ต่ำกว่า
ความซับซ้อน เหมาะกับ logic เรียบง่าย เหมาะกับ logic ซับซ้อน
Debugging ยากกว่า (บรรทัดเดียว) ง่ายกว่า (แยกบรรทัด)