Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

NullReferenceException ใน C#


ภาพรวม

NullReferenceException เกิดขึ้นเมื่อ พยายามเข้าถึงสมาชิก (field, property, method) ของออบเจ็กต์ที่เป็น null

ตัวอย่างที่ทำให้เกิด Exception

using System;

class Demo
{
    static void Main()
    {
        string str = null;
        if (str.Length > 0) // พยายามเข้าถึง Length ของ null
            Console.WriteLine(str);
    }
}

ข้อความข้อผิดพลาด

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

สาเหตุทั่วไป

  • ลืม initialize object: MyClass obj; obj.Method();
  • เมธอดคืนค่า null: GetUser().Name (ถ้า GetUser คืน null)
  • อาร์เรย์ของ reference types: string[] arr = new string[5]; arr[0].Length; (arr[0] เป็น null)
  • Unboxing null: object o = null; int i = (int)o;

วิธีป้องกัน

  • ตรวจสอบ null ก่อนใช้: if (str != null) ...
  • ใช้ null-conditional operator: str?.Length (คืน null หาก str เป็น null)
  • ใช้ null-coalescing: str ?? "default"
  • ใช้ ArgumentNullException.ThrowIfNull(arg) (.NET 6+) ในต้นเมธอด
  • Enable nullable reference types (#nullable enable) เพื่อเตือนตอน compile time