What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
IndexOutOfRangeException occurs when you access an array or span with an index that is negative or greater than or equal to its length. ArgumentOutOfRangeException occurs when you pass an invalid index to a collection method like List<T>[index] or string.Substring(). Both mean the same thing: you are trying to access an element that does not exist. The fix is to check bounds before accessing, use zero-based indexing correctly, and validate loop conditions.
IndexOutOfRangeException
Thrown when accessing arrays, Span<T>, or similar fixed-size structures:
ArgumentOutOfRangeException
Thrown by List<T>, string, and other collection types:
Common Causes
Off-by-One Error in Loops
Empty Collection Access
Hardcoded Index Assumptions
Multi-Dimensional Array Errors
Prevention Strategies
Bounds Checking
Using LINQ
Pattern Matching (C# 11+)
Range and Index Operators (C# 8+)
Debugging Tips
String-Specific Cases
Common Pitfalls
- Using
<=instead of<in loop conditions: Arrays and lists are zero-indexed, so valid indices range from0toLength - 1. Usingi <= arr.Lengthiterates one step too far. Always usei < arr.Length. - Assuming
Split()returns a minimum number of elements:"a,b".Split(',')returns 2 elements, but"a".Split(',')returns 1. Always checkparts.Lengthbefore accessing specific indices. - Accessing the last element with
arr[arr.Length]: The last valid index isarr.Length - 1, notarr.Length. Usearr[^1](C# 8+) orarr[arr.Length - 1]for the last element. - Not checking for empty collections before indexing:
list[0]on an empty list throwsArgumentOutOfRangeException. Always checklist.Count > 0or uselist.FirstOrDefault()for safe access. - Confusing row and column indices in 2D arrays:
array[row, col]— the first dimension is rows, the second is columns. Swapping them accesses out-of-bounds memory when the dimensions differ.
Summary
IndexOutOfRangeException— arrays, spans (index < 0 or index >= length)ArgumentOutOfRangeException— lists, strings, collections (invalid argument to a method)- Always use
< Length(not<= Length) in loop conditions - Check collection size before accessing specific indices
- Use
FirstOrDefault(),ElementAtOrDefault(), or bounds-checking helpers for safe access - Use
arr[^1](C# 8+) for safe last-element access syntax
Related reading

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.