.NET Exceptions – System.IndexOutOfRangeException

Making our way through the .NET Exception Handling series, today we’ll take a closer look at the System.IndexOutOfRangeException. As indicated by its name, the System.IndexOutOfRangeException is raised when attempts are made to access an invalid index of a collection, such as a list or array.

In this article we’ll dig deeper into the System.IndexOutOfRangeException, seeing where it resides within the .NET exception hierarchy, along with a few functional C# cod examples to illustrate how System.IndexOutOfRangeExceptions are typically thrown, so let’s get to it!

The Technical Rundown

When Should You Use It?

As usual, to begin examining the System.IndexOutOfRangeException in more detail we’ll start with the full code example and then explore what’s going on in more detail below.

To begin we have a simple Book class that inherits from our IBook interface, allowing us to create some basic objects for manipulation:

We then have a simple method in which we generate a new Book List, add a few books to it, and then perform a basic iteration over our book list using the index:

Unsurprisingly this outputs all our book records for us:

However, in our next method we try much the same thing but our index value is allowed to go up to library.Count. This will cause a problem because, like most programming languages, collections are zero-based so the largest index our library list contains is actually one less than the .Count property:

Sure enough this throws an error our way:

It’s worth noting that while the actual class type that was thrown there was a System.ArgumentOutOfRangeException (instead of a System.IndexOutOfRangeException), the error message clearly indicates that this is a problem with the provided index being out of range.

Another common technique is to change the values of an existing collection. There are many ways to accomplish this, but one method is to specify the collection element using the index of the element to be changed, which is what we’re doing in this next example method:

Here we access and change the last element in our collection by changing library[library.Count - 1] (the last index) and assigning it to a new Book instance. The output shows that our library has been updated with a different final book:

Now let’s try that again but this time we’ll be accessing an index of our library collection that doesn’t exist (library.Count, which is one value greater than the maximum index):

Sure enough this throws another exception our way, indicating that the index provided isn’t within the allowed bounds:

To get the most out of your own applications and to fully manage any and all .NET Exceptions, check out the Airbrake .NET Bug Handler, offering real-time alerts and instantaneous insight into what went wrong with your .NET code, along with built-in support for a variety of popular development integrations including: JIRA, GitHub, Bitbucket, and much more.