Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Các toán tử xử lý giá trị null trong C#

C# cung cấp 3 toán tử xử lý null:

1. Toán tử null-coalescing (??)

Lấy giá trị biến nếu không null, ngược lại dùng giá trị mặc định.

Thay thế: value != null ? value : "default" → value ?? "default"

string input = null;
string choice = input ?? "default_choice";
Console.WriteLine(choice); // default_choice

string finalChoice = choice ?? "not_chosen";
Console.WriteLine(finalChoice); // default_choice

2. Toán tử null-coalescing assignment (??=)

Trả về vế trái nếu không null, ngược lại gán vế phải vào vế trái. Khởi tạo giá trị mặc định nếu biến đang null.

Thay thế: if (result == null) result = "default"; → result ??= "default";

Hữu ích cho lazy property:

class Tax
{
    private Report _lengthyReport;
    public Report LengthyReport => _lengthyReport ??= CalculateLengthyReport();
    private Report CalculateLengthyReport() => new Report();
}

3. Toán tử null-conditional (?.)

Gọi phương thức an toàn: nếu instance null → trả null thay vì ném NullReferenceException.

Thay thế: instance == null ? null : instance.Method() → instance?.Method()


string input = null;
string result = input?.ToString();
Console.WriteLine(result); // null (in ra dòng trống)

Ví dụ tổng hợp

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); // (null)
    }
}

Kết quả đầu ra

default_choice
default_choice