This question already has an answer here:
I'm getting one of the following errors:
- "Index was out of range. Must be non-negative and less than the size of the collection"
- "Insertion index was out of range. Must be non-negative and less than or equal to size."
- "Index was outside the bounds of the array."
What does it mean, and how do I fix it?
See Also
IndexOutOfRangeException
ArgumentOutOfRangeException
Why does this error occur?
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 indexn-1
, wheren
is theSize
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 thanSize-1
, you're going to get an error.How indexing arrays works
When you declare an array like this:
The first and last elements in the array are
So when you write:
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
This works, because the loop starts at zero, and ends at
Length-1
becauseindex
is no longer less thanLength
.This, however, will throw an exception:
Notice the
<=
there?index
will now be out of range in the last loop iteration, because the loop thinks thatLength
is a valid index, but it is not.How other collections work
Lists work the same way, except that you generally use
Count
instead ofLength
. They still start at zero, and end atCount - 1
.However, you can also iterate through a list using
foreach
, avoiding the whole problem of indexing entirely:You cannot index an element that hasn't been added to a collection yet.