I'm getting one of the following errors:
What does it mean, and how do I fix it?
See Also
IndexOutOfRangeException
ArgumentOutOfRangeException
Generally, list index out of range means means that you are providing an index for which a list element does not exist.
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.
Solutions to Prevent IndexOutOfRangeException Solution 1: Get the total number of elements in a collection and then check the upper bound of a collection is one less than its number of elements. Solution 2: Use the try catch blocks to catche the IndexOutOfRangeException .
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0]; var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++) { Console.WriteLine(array[index]); }
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++) { Console.WriteLine(array[index]); }
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++) { Console.WriteLine(list[index]); }
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list) { Console.WriteLine(element.ToString()); }
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>(); list.Add("Zero"); list.Add("One"); list.Add("Two"); Console.WriteLine(list[3]); // Throws exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With