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

NullReferenceException ใน C# (Null Pointer Exception)

ใน C# ไม่มี NullPointerException` เหมือน Java แทนด้วย NullReferenceException เกิดขึ้นเมื่อพยายามเข้าถึงสมาชิก (Property, Method, Indexer) ของออบเจกต์ที่เป็น null

ตัวอย่างที่เกิด Exception

string str = null;
Console.WriteLine(str.Length); // ❌ NullReferenceException

การจัดการด้วย try-catch

try {
    string str = null;
    Console.WriteLine(str.Length);
} catch (NullReferenceException ex) {
    Console.WriteLine("ตัวแปรเป็น Null! รายละเอียด: " + ex.Message);
}

วิธีป้องกัน (Best Practices)

1. Null Conditional Operator (?.) - C# 6+

string str = null;
int? length = str?.Length; // คืนค่า null แทนที่จะ throw exception
Console.WriteLine(length ?? 0); // แสดง 0 ถ้าเป็น null

2. Null Coalescing Operator (??) - C# 2+

string name = null;
string displayName = name ?? "Guest"; // ใช้ "Guest" ถ้า name เป็น null

3. ตรวจสอบก่อนใช้ (Traditional)

if (str != null) {
    Console.WriteLine(str.Length);
}

4. Pattern Matching - C# 7+

if (str is string s) {
    Console.WriteLine(s.Length);
}

ตัวอย่างครบถ้วน

using System;

class Program {
    static void Main() {
        string input = null;
        
        // ❌ ความเสี่ยง
        try {
            Console.WriteLine(input.Length);
        } catch (NullReferenceException ex) {
            Console.WriteLine("จับได้: " + ex.Message);
        }
        
        // ✅ แนะนำ: ใช้ ?. และ ??
        Console.WriteLine("ความยาว: " + (input?.Length ?? 0));
        
        Console.ReadKey();
    }
}

สรุป

  • C# ใช้ NullReferenceException ไม่ใช่ NullPointerException
  • หลีกเลี่ยง try-catch สำหรับควบคุม Flow — ใช้ Null-conditional (?.) และ Null-coalescing (??) แทน
  • เปิดใช้ nullable reference types (C# 8+) เพื่อจับปัญหาได้ที่ Compile-time