Understanding IndexOutOfRangeException Exception in C#



It occurs when Index is outside the bounds of the array.

Let us see an example. We have declare an array with 5 elements and set the size as 5.

int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50;

Now, we try to add the value of an element that extends the size of our array i.e.

arr[5] = 60;

Above, we are trying to add element at 6th position.

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[5];          arr[0] = 10;          arr[1] = 20;          arr[2] = 30;          arr[3] = 40;          arr[4] = 50;          arr[5] = 60; // 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.
Updated on: 2020-04-13T12:31:00+05:30

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements