
You are interested in the IndexOutOfRangeException that has occurred in your program written in the C# language that uses array types. This exception will typically occur when a statement tries to access an element at an index greater than the maximum allowable index.
This C# exception article demonstrates IndexOutOfRangeException.
First this program demonstrates the usage of the array index access in the C# programming language. When you create an array of many elements, as shown in the program, you can access those elements through the indices of zero through the maximum length minus one. So for an array of 100 elements, you can access array[0] through array[99]. You can load and store values into these elements, which are considered variables and not values.
Program that accesses array out of bounds [C#]
class Program
{
static void Main()
{
// Allocate an array of one-hundred integers.
// ... Then assign to positions in the array.
// ... Assigning past the last element will throw.
int[] array = new int[100];
array[0] = 1;
array[10] = 2;
array[200] = 3;
}
}
Exception thrown by program
Unhandled Exception: System.IndexOutOfRangeException:
Index was outside the bounds of the array.
at Program.Main() in ...Program.cs:line 8
Encountering the exception. This program text introduces the Main entry point and in this method it uses a new array of length 100. This means that the array is a reference to object data of size 100 integers. You can access the array elements through array subscripts, as with array[0], array[1], through array[99]. The top index you can access is equal to the total length minus one (100 - 1). If you access an index past the index 99, you will always get an IndexOutOfRangeException, as the program demonstrates.

Avoiding the exception. To avoid the IndexOutOfRangeException, typically you can insert bounds checks, as with an if statement in the C# language. An alternative is to simply make the array length much larger when you allocate it. If you can avoid the if statement checks altogether, you can improve performance in some cases, but this can result in code that is prone to failure.
If StatementNegative array indices. Although this is not demonstrated by the program, you will encounter the IndexOutOfRangeException if you try to assign to an index in an array that is negative. In the C# language, native arrays are indexed beginning at zero. In other words, the first element is always available at index zero. There are ways to simulate non-zero based arrays.

Here we saw the IndexOutOfRangeException. We contextualized this exception in a complete program with an explanation of the relation between array lengths and array indices. You can always access the array indexes up to the array length minus one. This off-by-one difference is critical to keep in mind in some programs as errors in this translation can be very serious.
Exception Handling