Home
C#
IndexOutOfRangeException
This page was last reviewed on Aug 17, 2021.
Dot Net Perls
IndexOutOfRangeException. This C# exception will typically occur when a statement tries to access an element at an index greater than the maximum allowable index.
This error happens in C# programs that use array types. A negative index will also cause this exception. If-statements should be added to protect against invalid accesses.
Exception
Array
Array Length
Exception example. When you create an array of many elements, you can access those elements through the indices of zero through the maximum length minus one.
Note This means that for an array of 100 elements, you can access array[0] through array[99].
Important The top index equals the total length minus one. If you access an index past 99, you get an IndexOutOfRangeException.
Detail You can load and store values into these elements, which are considered variables and not values.
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; } }
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at Program.Main() in ...Program.cs:line 8
To avoid the exception, you can insert bounds checks, as with an if-statement. An alternative is to simply make the array length much larger when you allocate it.
if
Negative array indices. You will encounter the IndexOutOfRangeException if you try to assign to an index in an array that is negative. In C# arrays are indexed beginning at zero.
Note The first element is always available at index zero. There are ways to simulate non-zero based arrays.
Summary. Here we saw the IndexOutOfRangeException. We explained the relation between array lengths and array indices. You can always access the array indexes up to the array length minus one.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 17, 2021 (image).
Home
Changes
© 2007-2024 Sam Allen.