Follow @endyourif rss Facebook LinkedIn

Understanding IndexOutOfRangeException and ArgumentOutOfRangeException Understanding IndexOutOfRangeException and ArgumentOutOfRangeException

Published on Mar 2, 2020

You've received the following error: Index was outside the bounds of the array with an IndexOutOfRangeException or you received: An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code Additional information: Index was out of range. Must be non-negative and less than the size of the collection with an ArgumentOutOfRangeException. So what gives? Here is what you need to know.

What is IndexOutOfRangeException: Index was outside the bounds of the array

This exception occurs when you try to access a collection item by using an invalid index. An index that is invalid happens when it is lower than the collection's lower bound or greater than or equal to the number of elements it contains. For example -1 or if there were 4 elements, using the number 4 because collections start at a 0; commonly called 0-based indexing.

What is An exception of type System.ArgumentOutOfRangeException

An ArgumentOutOfRangeException is very similar to IndexOutOfRangeException exception where you are trying to access an index that is not within the bounds of the list. Typically the ArgumentOutOfRangeException is thrown when using List whereas IndexOutOfRangeException more commonly occurs with arrays.

How to solve IndexOutOfRangeException and ArgumentOutOfRangeException

The most common way these exceptions are thrown when you are using search functions like IndexOf or FindIndex. When you are using these functions, if the value is not returned then the result returns -1 which is not inside the lower bounds of the array.

After performing a function call like this adding a simple check like: if (index > -1) or if (index >= 0) proceed. You can also check that a value is not trying to access outside of the array's upper bounds by doing something like: if (index < array.Length) proceed.

Tags: ASP.NET MVC and Web API Tutorial | c# | exception

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP