What is IndexOutOfRangeException in C#
594
07-Jun-2024
Ravi Vishwakarma
07-Jun-2024The IndexOutOfRangeException is an exception in C#, Which arises when you access an index that is not present in an array, collection, or other indexed data structure that is outside the valid range of indices. This typically happens when you try to access an element at an index that is less than zero or greater than or equal to the length of the collection.
Here's an example of how this exception might occur:
When you run this code, it will throw an
IndexOutOfRangeExceptionbecause the valid indices for thenumbersarray range from 0 to 4 (inclusive), but we attempted to access index 5, which doesn't exist.To prevent this exception, always ensure that you are accessing indices within the valid range of the collection. You can use conditional statements or loops to check the bounds before accessing elements or use methods like
TryGetValuefor dictionaries orElementAtOrDefaultfor LINQ queries, which handle out-of-range situations gracefully by returning default values instead of throwing exceptions.