Understanding Array IndexOutofBoundsException in C#


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.

Example

 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
      }
   }
}

Output

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

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 13-Apr-2020

424 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements