Ternary Operator (Conditional Operator) ใน C#
Ternary Operator ? : เป็น Operator เติมที่รับ 3 Operand: condition ? trueExpression : falseExpression ใช้แทน if-else แบบสั้นๆ
ไวยากรณ์
variable = condition ? valueIfTrue : valueIfFalse;
ตัวอย่างพื้นฐาน
using System;
namespace DEMO
{
class Program
{
static void Main(string[] args)
{
int a = 10;
int b;
// เงื่อนไขเท็จ -> ค่า 30
b = (a == 1) ? 20 : 30;
Console.WriteLine($"Value of b is {b}"); // 30
// เงื่อนไขจริง -> ค่า 20
b = (a == 10) ? 20 : 30;
Console.WriteLine($"Value of b is {b}"); // 20
Console.ReadLine();
}
}
}
ผลลัพธ์
Value of b is 30
Value of b is 20
การใช้งานขั้นสูง
1. Nested Ternary (ไม่แนะนำ - อ่านยาก)
string result = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" : "F";
2. กับ Null Coalescing (??)
string name = input ?? "Default Name"; // ถ้า input null ใช้ "Default Name"
3. ใน Expression-bodied Members
public string GetStatus(bool isActive) => isActive ? "Active" : "Inactive";
public int Max(int a, int b) => a > b ? a : b;
4. Throw Expression (C# 7.0+)
string name = input ?? throw new ArgumentNullException(nameof(input));
ข้อควรระวัง
- Type ของ True/False Expression ต้องเข้ากันได้ (Implicit Conversion)
- ไม่ใช่ Statement ไม่สามารถวางโค้ดหลายบรรทัดได้ (ใช้ if-else แทน)
- Side Effects ใน Expression ควรหลีกเลี่ยง
เปรียบเทียบ If-Else vs Ternary
| ลักษณะ | if-else | Ternary |
|---|---|---|
| Readability (Complex) | ดี | แย่ |
| Conciseness (Simple) | เยอะ | กระชับ |
| Expression/Statement | Statement | Expression |
| Debugging | ง่าย | ยาก (Single Line) |