Computer >> Máy Tính >  >> Lập trình >> C#

Hiểu Array IndexOutofBoundsException trong C #

Array IndexOutofBoundsException xảy ra trong Java. Tương đương với nó trong C # là IndexOutOfRangeException.

IndexOutOfRangeException xảy ra khi Chỉ mục 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; // this shows an error
      }
   }
}

Đầu ra

Sau đây là kết quả đầu ra. Nó hiển thị lỗi sau -

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