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?.cthiếu?..
Cách phòng tránh
| Kỹ thuật | Ví dụ |
|---|---|
| Null check | if (str != null) { ... } |
| Null-conditional (?.) | str?.Length (trả về int?) |
| Null-coalescing (??) | str ?? "default" |
| TryGetValue / ContainsKey | Cho Dictionary |
| Guard clause | if (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
ArgumentNullExceptioncho validation tham số public method. - Bật
nullablecontext để compiler cảnh báo tại compile time.