IndexOutOfRangeException Class

 

The exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

System::Object
  System::Exception
    System::SystemException
      System::IndexOutOfRangeException

[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class IndexOutOfRangeException sealed : SystemException

NameDescription
System_CAPS_pubmethodIndexOutOfRangeException()

Initializes a new instance of the IndexOutOfRangeException class.

System_CAPS_pubmethodIndexOutOfRangeException(String^)

Initializes a new instance of the IndexOutOfRangeException class with a specified error message.

System_CAPS_pubmethodIndexOutOfRangeException(String^, Exception^)

Initializes a new instance of the IndexOutOfRangeException class with a specified error message and a reference to the inner exception that is the cause of this exception.

NameDescription
System_CAPS_pubpropertyData

Gets a collection of key/value pairs that provide additional user-defined information about the exception.(Inherited from Exception.)

System_CAPS_pubpropertyHelpLink

Gets or sets a link to the help file associated with this exception.(Inherited from Exception.)

System_CAPS_pubpropertyHResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.(Inherited from Exception.)

System_CAPS_pubpropertyInnerException

Gets the Exception instance that caused the current exception.(Inherited from Exception.)

System_CAPS_pubpropertyMessage

Gets a message that describes the current exception.(Inherited from Exception.)

System_CAPS_pubpropertySource

Gets or sets the name of the application or the object that causes the error.(Inherited from Exception.)

System_CAPS_pubpropertyStackTrace

Gets a string representation of the immediate frames on the call stack.(Inherited from Exception.)

System_CAPS_pubpropertyTargetSite

Gets the method that throws the current exception.(Inherited from Exception.)

NameDescription
System_CAPS_pubmethodEquals(Object^)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodGetBaseException()

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.(Inherited from Exception.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetObjectData(SerializationInfo^, StreamingContext)

When overridden in a derived class, sets the SerializationInfo with information about the exception.(Inherited from Exception.)

System_CAPS_pubmethodGetType()

Gets the runtime type of the current instance.(Inherited from Exception.)

System_CAPS_pubmethodToString()

Creates and returns a string representation of the current exception.(Inherited from Exception.)

An IndexOutOfRangeException exception is thrown when an invalid index is used to access a member of an array or a collection, or to read or write from a particular location in a buffer. This exception inherits from the Exception class but adds no unique members.

Typically, an IndexOutOfRangeException exception is thrown as a result of developer error. Instead of handling the exception, you should diagnose the cause of the error and correct your code. The most common causes of the error are:

  • Forgetting that the upper bound of a collection or a zero-based array is one less than its number of members or elements, as the following example illustrates.

    No code example is currently available or this language may not be supported.

    To correct the error, you can use code like the following.

    No code example is currently available or this language may not be supported.

    Alternately, instead of iterating all the elements in the array by their index, you can use the (in C#) or the (in Visual Basic).

  • Attempting to assign an array element to another array that has not been adequately dimensioned and that has fewer elements than the original array. The following example attempts to assign the last element in the value1 array to the same element in the value2 array. However, the value2 array has been incorrectly dimensioned to have six instead of seven elements. As a result, the assignment throws an IndexOutOfRangeException exception.

    No code example is currently available or this language may not be supported.
  • Using a value returned by a search method to iterate a portion of an array or collection starting at a particular index position. If you forget to check whether the search operation found a match, the runtime throws an IndexOutOfRangeException exception, as shown in this example.

    No code example is currently available or this language may not be supported.

    In this case, the List<T>::IndexOf method returns -1, which is an invalid index value, when it fails to find a match. To correct this error, check the search method's return value before iterating the array, as shown in this example.

    No code example is currently available or this language may not be supported.
  • Trying to use or enumerate a result set, collection, or array returned by a query without testing whether the returned object has any valid data.

  • Using a computed value to define the starting index, the ending index, or the number of items to be iterated. If the result of the computation is unexpected, it might result in an IndexOutOfRangeException exception. You should check your program's logic in calculating the index value and validate the value before iterating the array or collection. The following conditions must all be true; otherwise, an IndexOutOfRangeException exception is thrown:

    • The starting index must be greater than or equal to Array::GetLowerBound for the dimension of the array that you want to iterate, or greater than or equal to 0 for a collection.

    • The ending index cannot exceed Array::GetUpperBound for the dimension of the array that you want to iterate, or cannot be greater than or equal to the Count property of a collection.

    • The following equation must be true for the dimension of the array that you want to iterate:

      start_index >= lower_bound And start_index + items_to_iterate – 1 <= upper_bound
      

      For a collection, the following equation must be true:

      start_index >= 0 And start_index + items_to_iterate <= Count
      
      System_CAPS_tipTip

      The starting index of an array or collection can never be a negative number.

  • Assuming that an array must be zero-based. Arrays that are not zero-based can be created by the Array::CreateInstance(Type^, array<Int32>^, array<Int32>^) method and can be returned by COM interop, although they aren’t CLS-compliant. The following example illustrates the IndexOutOfRangeException that is thrown when you try to iterate a non-zero-based array created by the Array::CreateInstance(Type^, array<Int32>^, array<Int32>^) method.

    No code example is currently available or this language may not be supported.

    To correct the error, as the following example does, you can call the GetLowerBound method instead of making assumptions about the starting index of an array.

    No code example is currently available or this language may not be supported.

    Note that when you call the GetLowerBound method to get the starting index of an array, you should also call the Array::GetUpperBound(Int32) method to get its ending index.

  • Confusing an index and the value at that index in a numeric array or collection. This issue usually occurs when using the foreach statement (in C#) or the For Each statement (in Visual Basic). The following example illustrates the problem.

    No code example is currently available or this language may not be supported.

    The iteration construct returns each value in an array or collection, not its index. To eliminate the exception, use this code.

    No code example is currently available or this language may not be supported.
  • Providing an invalid column name to the DataView::Sort property.

  • Violating thread safety. Operations such as reading from the same StreamReader object, writing to the same StreamWriter object from multiple threads, or enumerating the objects in a Hashtable from different threads can throw an IndexOutOfRangeException if the object isn’t accessed in a thread-safe way. This exception is typically intermittent because it relies on a race condition.

Using hard-coded index values to manipulate an array is likely to throw an exception if the index value is incorrect or invalid, or if the size of the array being manipulation is unexpected. To prevent an operation from throwing an IndexOutOfRangeException exception, you can do the following:

  • Iterate the elements of the array using the foreach statement (in C#) or the For Each...Next construct (in Visual Basic) instead of iterating elements by index.

  • Iterate the elements by index starting with the index returned by the Array::GetLowerBound method and ending with the index returned by the Array::GetUpperBound method.

  • If you are assigning elements in one array to another, ensure that the target array has at least as many elements as the source array by comparing their Array::Length properties.

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

The following intermediate language (IL) instructions throw IndexOutOfRangeException:

  • ldelem.<type>

  • ldelema

  • stelem.<type>

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

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show: