C# มีออเปอเรเตอร์ 3 ตัวสำหรับจัดการ Null:
1. Null-Coalescing Operator (??)
คืนค่าตัวแปรหากไม่ใช่ Null มิฉะนั้นคืนค่า Default ที่ระบุ แทน Ternary Operator:
// เดิม string resultOne = value != null ? value : "default_value"; // ใหม่ string resultTwo = value ?? "default_value";
ตัวอย่าง
string input = null; string choice = input ?? "default_choice"; // default_choice string finalChoice = choice ?? "not_chosen"; // default_choice
2. Null-Coalescing Assignment Operator (??=)
คืนค่าด้านซ้ายหากไม่ใช่ Null มิฉะนั้นกำหนดค่าด้านขวาให้ตัวแปรด้านซ้าย แทน if-null-then-assign:
// เดิม if (result == null) result = "default_value"; // ใหม่ result ??= "default_value";
เหมาะกับ Lazy Properties:
class Tax
{
private Report _lengthyReport;
public Report LengthyReport => _lengthyReport ??= CalculateLengthyReport();
private Report CalculateLengthyReport() => new Report();
}3. Null-Conditional Operator (?.)
เรียกเมธอด/Property ได้ปลอดภัย หาก Instance เป็น Null คืน Null แทนที่จะโยน NullReferenceException:
// เดิม string result = instance == null ? null : instance.Method(); // ใหม่ string result = instance?.Method();
ตัวอย่าง
string input = null; string result = input?.ToString(); // null (ไม่โยน Exception)
ตัวอย่างโค้ดรวม
using System;
class Program
{
static void Main()
{
string input = null;
string choice = input ?? "default_choice";
Console.WriteLine(choice); // default_choice
string finalChoice = choice ?? "not_chosen";
Console.WriteLine(finalChoice); // default_choice
string foo = null;
string answer = foo?.ToString();
Console.WriteLine(answer); // (prints nothing - null)
}
}ผลลัพธ์
default_choice default_choice