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

Array IndexOutOfBoundsException ใน C#: เทียบเท่า Java

ใน Java มี ArrayIndexOutOfBoundsException ใน C# เทียบเท่าคือ IndexOutOfRangeException (ไม่มี "Bounds" ในชื่อ) เกิดเมื่อเข้าถึง Array ด้วย Index ไม่ถูกต้อง

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

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[3]; // Index 0, 1, 2
            
            arr[0] = 5;
            arr[1] = 7;
            arr[2] = 8;
            
            // ERROR: Index 4 ไม่มีอยู่ (Max = 2)
            arr[4] = 24; // IndexOutOfRangeException
        }
    }
}

ผลลัพธ์

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

ความแตกต่าง Java vs C#

คุณสมบัติJavaC#
Exception NameArrayIndexOutOfBoundsExceptionIndexOutOfRangeException
Inheritanceextends IndexOutOfBoundsExceptionextends Exception (โดยตรง)
Array Access CheckRuntime (JVM)Runtime (CLR)
Zero-basedใช่ใช่

การป้องกัน (เหมือนกันทั้งคู่)

  • ตรวจสอบ index >= 0 && index < array.Length ก่อนเข้าถึง
  • ใช้ foreach แทน Index-based Loop
  • ใช้ List<T> ที่มี Count Property ชัดเจน
  • Unit Test Edge Cases (Empty, Single, Boundary)

หมายเหตุ: C# มี ArgumentOutOfRangeException สำหรับ Collection Methods (List.Insert, String.Substring, etc.) ที่แยกจาก IndexOutOfRangeException (สำหรับ Array Indexer โดยตรง)