System.IndexOutOfRangeException Class

The exception that is thrown when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited.

See Also: IndexOutOfRangeException Members

Syntax

[System.Runtime.InteropServices.ComVisible(true)]
public sealed class IndexOutOfRangeException : SystemException

Remarks

The following Microsoft intermediate language (MSIL) instructions throw IndexOutOfRangeException :

IndexOutOfRangeException uses the HRESULT COR_E_INDEXOUTOFRANGE, which has the value 0x80131508.

The most common causes of this exception are miscalculating a lookup index, or using the wrong start or end point when iterating. For other causes, see Troubleshooting Exceptions: System.IndexOutOfRangeException.

For a list of initial property values for an instance of IndexOutOfRangeException, see the IndexOutOfRangeException constructors.

Thread Safety

All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe.

Example

The following example demonstrates an error that causes a IndexOutOfRangeException exception.

C# Example

using System;
public class IndexRangeTest {
 public static void Main() {
   int[] array = {0,0,0};
   try {
     for (int i = 0; i<4; i++) {
       Console.WriteLine("array[{0}] = {1}",i,array[i]);
     }
   }
   catch (IndexOutOfRangeException e) {
     Console.WriteLine("Error: {0}",e);
   }
 }
}
   

The output is

Example

array[0] = 0
array[1] = 0
array[2] = 0
Error: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at IndexRangeTest.Main()
 

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0