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

NullReferenceException trong C#


Giới thiệu

NullReferenceException ném ra khi truy cập thành viên (field, property, method) trên tham chiếu null. Đây là ngoại lệ phổ biến nhất trong C#.

Ví dụ gây ra ngoại lệ

using System;

class Demo
{
    static void Main()
    {
        string str = null;
        if (str.Length > 0) // Ném NullReferenceException tại str.Length
        {
            Console.WriteLine(str);
        }
    }
}

Kết quả

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
   at Demo.Main()

Các nguyên nhân thường gặp

  • Biến chưa khởi tạo: string s; s.Length (compile error cho local, nhưng field có thể null).
  • Gán null tường minh: obj = null; obj.Method().
  • Phương thức trả về null: GetUser().Name (nếu GetUser trả null).
  • Phần tử mảng/List null: arr[0].ToString() (nếu arr[0] = null).
  • Chuỗi gọi (chained): a?.b?.c thiếu ?..

Cách phòng tránh

Kỹ thuậtVí dụ
Null checkif (str != null) { ... }
Null-conditional (?.)str?.Length (trả về int?)
Null-coalescing (??)str ?? "default"
TryGetValue / ContainsKeyCho Dictionary
Guard clauseif (arg == null) throw new ArgumentNullException(...);
Nullable reference types (C# 8+)#nullable enable, string? vs string

Ví dụ an toàn

string str = GetStringOrNull();
// Cách 1
if (str != null && str.Length > 0) { ... }
// Cách 2 (C# 6+)
if (str?.Length > 0) { ... }
// Cách 3
int len = str?.Length ?? 0;

Lưu ý

  • NullReferenceException là bug logic, không nên catch để xử lý (trừ boundary layer).
  • Dùng ArgumentNullException cho validation tham số public method.
  • Bật nullable context để compiler cảnh báo tại compile time.