Export (0) Print
Expand All

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.

System.Object
  System.Exception
    System.SystemException
      System.IndexOutOfRangeException

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

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

The IndexOutOfRangeException type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIndexOutOfRangeException()Initializes a new instance of the IndexOutOfRangeException class.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIndexOutOfRangeException(String)Initializes a new instance of the IndexOutOfRangeException class with a specified error message.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIndexOutOfRangeException(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.
Top

  NameDescription
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsDataGets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsHelpLinkGets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public propertySupported in .NET for Windows Store appsHResultGets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsInnerExceptionGets the Exception instance that caused the current exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMessageGets a message that describes the current exception. (Inherited from Exception.)
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsSourceGets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsStackTraceGets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public propertyTargetSiteGets the method that throws the current exception. (Inherited from Exception.)
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetBaseExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetObjectDataWhen overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the runtime type of the current instance. (Inherited from Exception.)

In XNA Framework 3.0, this member is inherited from Object.GetType().


In Portable Class Library Portable Class Library, this member is inherited from Object.GetType().


In .NET for Windows Store apps Windows 8, this member is inherited from Object.GetType().
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringCreates and returns a string representation of the current exception. (Inherited from Exception.)
Top

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.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<Char> characters = new List<Char>();
          characters.InsertRange(0, new Char[] { 'a', 'b', 'c', 'd', 'e', 'f' } );
          for (int ctr = 0; ctr <= characters.Count; ctr++)
             Console.Write("'{0}'    ", characters[ctr]);
       }
    }
    // The example displays the following output: 
    //    'a'    'b'    'c'    'd'    'e'    'f' 
    //    Unhandled Exception:  
    //    System.ArgumentOutOfRangeException:  
    //    Index was out of range. Must be non-negative and less than the size of the collection. 
    //    Parameter name: index 
    //       at Example.Main()
    

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

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<Char> characters = new List<Char>();
          characters.InsertRange(0, new Char[] { 'a', 'b', 'c', 'd', 'e', 'f' } );
          for (int ctr = 0; ctr < characters.Count; ctr++)
             Console.Write("'{0}'    ", characters[ctr]);
       }
    }
    // The example displays the following output: 
    //        'a'    'b'    'c'    'd'    'e'    'f'
    

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

  • 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.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       static List<int> numbers = new List<int>();
    
       public static void Main()
       {
          int startValue; 
          string[] args = Environment.GetCommandLineArgs();
          if (args.Length < 2) 
             startValue = 2;
          else  
             if (! Int32.TryParse(args[1], out startValue))
                startValue = 2;
    
          ShowValues(startValue);
       }
    
       private static void ShowValues(int startValue)
       {   
          // Create a collection with numeric values. 
          if (numbers.Count == 0)  
             numbers.AddRange( new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} );
    
          // Get the index of a startValue.
          Console.WriteLine("Displaying values greater than or equal to {0}:",
                            startValue);
          int startIndex = numbers.IndexOf(startValue);
          // Display all numbers from startIndex on. 
          for (int ctr = startIndex; ctr < numbers.Count; ctr++)
             Console.Write("    {0}", numbers[ctr]);
       }
    }
    // The example displays the following output if the user supplies 
    // 7 as a command-line parameter: 
    //    Displaying values greater than or equal to 7: 
    //     
    //    Unhandled Exception: System.ArgumentOutOfRangeException:  
    //    Index was out of range. Must be non-negative and less than the size of the collection. 
    //    Parameter name: index 
    //       at System.Collections.Generic.List`1.get_Item(Int32 index) 
    //       at Example.ShowValues(Int32 startValue) 
    //       at Example.Main()
    

    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.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       static List<int> numbers = new List<int>();
    
       public static void Main()
       {
          int startValue; 
          string[] args = Environment.GetCommandLineArgs();
          if (args.Length < 2) 
             startValue = 2;
          else  
             if (! Int32.TryParse(args[1], out startValue))
                startValue = 2;
    
          ShowValues(startValue);
       }
    
       private static void ShowValues(int startValue)
       {   
          // Create a collection with numeric values. 
          if (numbers.Count == 0)  
             numbers.AddRange( new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} );
    
          // Get the index of startValue. 
          int startIndex = numbers.IndexOf(startValue);
          if (startIndex < 0) {
             Console.WriteLine("Unable to find {0} in the collection.", startValue);
          }
          else {
             // Display all numbers from startIndex on.
             Console.WriteLine("Displaying values greater than or equal to {0}:",
                            startValue);
             for (int ctr = startIndex; ctr < numbers.Count; ctr++)
                Console.Write("    {0}", numbers[ctr]);
          }
       }
    }
    // The example displays the following output if the user supplies 
    // 7 as a command-line parameter: 
    //      Unable to find 7 in the collection.
    
  • 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
      
      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, Int32[], 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, Int32[], Int32[]) method.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Array values = Array.CreateInstance(typeof(int), new int[] { 10 }, 
                                              new int[] { 1 });
          int value = 2;
          // Assign values. 
          for (int ctr = 0; ctr < values.Length; ctr++) {
             values.SetValue(value, ctr);
             value *= 2;
          }
    
          // Display values. 
          for (int ctr = 0; ctr < values.Length; ctr++)
             Console.Write("{0}    ", values.GetValue(ctr));
       }
    }
    // The example displays the following output: 
    //    Unhandled Exception:  
    //    System.IndexOutOfRangeException: Index was outside the bounds of the array. 
    //       at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices) 
    //       at System.Array.SetValue(Object value, Int32 index) 
    //       at Example.Main()
    

    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.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Array values = Array.CreateInstance(typeof(int), new int[] { 10 }, 
                                              new int[] { 1 });
          int value = 2;
          // Assign values. 
          for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) {
             values.SetValue(value, ctr);
             value *= 2;
          }
    
          // Display values. 
          for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
             Console.Write("{0}    ", values.GetValue(ctr));
       }
    }
    // The example displays the following output: 
    //        2    4    8    16    32    64    128    256    512    1024
    

    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.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          // Generate array of random values. 
          int[] values = PopulateArray(5, 10);
          // Display each element in the array. 
          foreach (var value in values)
             Console.Write("{0}   ", values[value]);
       }
    
       private static int[] PopulateArray(int items, int maxValue)
       {
          int[] values = new int[items];
          Random rnd = new Random();
          for (int ctr = 0; ctr < items; ctr++)
             values[ctr] = rnd.Next(0, maxValue + 1);   
    
          return values;                                                      
       }
    }
    // The example displays output like the following: 
    //    6   4   4 
    //    Unhandled Exception: System.IndexOutOfRangeException:  
    //    Index was outside the bounds of the array. 
    //       at Example.Main()
    

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

    using System;
    
    public class Example
    {
       public static void Main()
       {
          // Generate array of random values. 
          int[] values = PopulateArray(5, 10);
          // Display each element in the array. 
          foreach (var value in values)
             Console.Write("{0}   ", value);
       }
    
       private static int[] PopulateArray(int items, int maxValue)
       {
          int[] values = new int[items];
          Random rnd = new Random();
          for (int ctr = 0; ctr < items; ctr++)
             values[ctr] = rnd.Next(0, maxValue + 1);   
    
          return values;                                                      
       }
    }
    // The example displays output like the following: 
    //        10   6   7   5   8
    
  • 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.

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.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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