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

วิธีจับ Null Reference Exception ใน C#

NullReferenceException เกิดเมื่อเข้าถึง Member ของ Object ที่เป็น null

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

string str = null;
int len = str.Length;  // NullReferenceException!

วิธีป้องกัน: Null Check

using System;

class Program
{
    static void Main()
    {
        int[] arr = new int[5] {1, 2, 3, 4, 5};
        Display(arr);
        
        arr = null;
        Display(arr); // ปลอดภัยแล้ว
    }
    
    static void Display(int[] arr)
    {
        // Null Check ก่อนใช้งาน
        if (arr == null)
        {
            Console.WriteLine("Array is null");
            return;
        }
        
        Console.WriteLine("Rank: " + arr.Rank);
    }
}

ผลลัพธ์

Rank: 1
Array is null

รูปแบบ Null Checking ทันสมัย (C# 6+)

1. Null-Conditional Operator (?.)

int? length = str?.Length; // ถ้า str=null คืน null, ไม่โยน Exception

2. Null-Coalescing Operator (??)

int length = str?.Length ?? 0; // ถ้า null ให้ 0

3. Null-Coalescing Assignment (??=) - C# 8+

str ??= "Default Value"; // กำหนดค่าเฉพาะเมื่อ null

4. Pattern Matching (C# 7+)

if (arr is null) { ... }
if (arr is not null) { ... }

Best Practices

  • Validate Input ที่ Entry Points (Constructor, Public Methods)
  • ใช้ ArgumentNullException.ThrowIfNull(arg) (.NET 6+)
  • Design โดยหลีกเลี่ยง Null (Option Type, Null Object Pattern)
  • Enable Nullable Reference Types: <Nullable>enable</Nullable> ใน .csproj