ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection
Console
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
The same mistake as IndexOutOfRangeException, on a List instead of an array: the index was negative or not less than Count.
Read the Console line first
Check the line in the stack trace for list[i], RemoveAt(i) or Insert(i). Log i and list.Count before it.
Common causes
Removing items in a forward loop
RemoveAt shifts every later item down by one, so a forward loop skips items and its last index runs past the shrinking Count.
Reading the first item of an empty list
list[0] fails when nothing has been added yet, for example an inventory before the first pickup.
The fix
Fix
C#
// Walk backwards so removals do not shift what is left to visit
for (int i = enemies.Count - 1; i >= 0; i--)
{
if (enemies[i].IsDead) enemies.RemoveAt(i);
}
// Or in one call
enemies.RemoveAll(e => e.IsDead);Stop it coming back
Remove from lists with RemoveAll or a reverse loop, and check Count before reading a fixed index.
Questions
- How do I remove items from a list safely while looping?
- Loop backwards with
for (int i = list.Count - 1; i >= 0; i--), so removing an item never shifts the ones you have not visited yet, or uselist.RemoveAll(x => x.IsDead). Removing inside a foreach loop throws a different error, Collection was modified. - Which method threw it?
- The stack trace names it. Besides list indexing,
List.Insert,RemoveAt,string.SubstringandRandom.Range-based indices are the usual sources. The parameter name in the message (index, startIndex, length) tells you which argument was out of range. - How do I read the first item only when there is one?
- Check
list.Count > 0first, or use a helper that returns a default. With System.Linq,list.FirstOrDefault()returns null (or default) on an empty list instead of throwing.
Scripts that avoid it
Related errors
Got a different error? Paste it into the error lookup.