Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Hiểu về Array IndexOutOfBoundsException trong C#


Array IndexOutOfBoundsException xảy ra trong Java. Tương đương của nó trong C# là IndexOutOfRangeException.

IndexOutOfRangeException xảy ra khi chỉ mục (Index) nằm ngoài giới hạn của mảng.

Ví dụ

using System; 
using System.IO; 
using System.Collections.Generic; 

namespace Demo { 
    class Program { 
        static void Main(string[] args) { 
            int[] arr = new int[3]; 
            arr[0] = 5; 
            arr[1] = 7; 
            arr[2] = 8; 
            arr[4] = 24; // này báo lỗi 
        } 
    } 
}

Kết quả

Kết quả sau được hiển thị. Nó báo lỗi sau:

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