เกิดขึ้นเมื่อดัชนีอยู่นอกขอบเขตของอาร์เรย์
เรามาดูตัวอย่างกัน เราได้ประกาศอาร์เรย์ที่มี 5 องค์ประกอบและกำหนดขนาดเป็น 5
int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50;
ตอนนี้เราพยายามเพิ่มค่าขององค์ประกอบที่ขยายขนาดของอาร์เรย์ของเรา นั่นคือ
arr[5] = 60;
ด้านบนเรากำลังพยายามเพิ่มองค์ประกอบที่ 6 th ตำแหน่ง
ตัวอย่าง
using System;
using System.IO;
using System.Collections.Generic;
namespace Demo {
class Program {
static void Main(string[] args) {
int[] arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
arr[5] = 60; // this shows an error
}
}
} ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ มันแสดงข้อผิดพลาดต่อไปนี้ -
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.