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

Learning faster. Every day.