Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

IndexOutOfRangeException

Reference for IndexOutOfRangeException in C#: why array and span indexes fail, off-by-one errors, ArgumentOutOfRangeException for lists, and safe indexing.

IndexOutOfRangeException is thrown when you index an array (or a Span<T> or a string) with an index that is negative or not smaller than its length. The runtime checks every array access, so C# never reads memory outside the array.

Valid indexes run from 0 to Length - 1. Most occurrences are off-by-one mistakes in loops. Note that List<T> and string behave differently: they throw ArgumentOutOfRangeException for a bad index.

C#
int[] numbers = [10, 20, 30];
Console.WriteLine(numbers[3]);   // throws IndexOutOfRangeException

Try it

C# Off-by-one and negative indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Arrays versus lists and strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public sealed class IndexOutOfRangeException : SystemException
{
    public IndexOutOfRangeException();
    public IndexOutOfRangeException(string? message);
    public IndexOutOfRangeException(string? message, Exception? innerException);
}

The type adds no members. The message is "Index was outside the bounds of the array." for built-in arrays.

Collection Exception for a bad index
T[] and Span<T> IndexOutOfRangeException
List<T> ArgumentOutOfRangeException
string indexer IndexOutOfRangeException
Dictionary key lookup KeyNotFoundException

Usage notes

  • Loop bound: use i < array.Length, not <=. Prefer foreach when you do not need the index.
  • Index from end: array[^1] is the last item. array[^0] is out of range because the index one past the end is invalid for element access.
  • Empty arrays: array[0] on an empty array throws. Check Length first.
  • Bounds-check elimination. The JIT removes checks when it can prove an index is safe, such as in for (int i = 0; i < a.Length; i++).
  • Slices do not throw for valid ranges. array[1..3] creates a copy and throws ArgumentOutOfRangeException if the range is invalid.
  • Never catch this to continue. It signals a logic error; fix the index calculation.
  • Multi-dimensional arrays check each dimension separately.
  • unsafe pointer code and Unsafe APIs skip the checks and can corrupt memory, so avoid them unless profiling demands it.