Understanding Array IndexOutofBoundsException in C#

CsharpProgrammingServer Side Programming

Array IndexOutofBoundsException occurs in Java. The equivalent of it in C# is IndexOutOfRangeException.

The IndexOutOfRangeException occurs when Index is outside the bounds of the array.


 Live Demo

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


The following is the output. It shows the following error −

Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
Published on 14-Sep-2018 14:50:22