Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index out of range exception vs argument out of range exception

When working from a list object, checking against an index that is out of range, for example

List<MyObject> allServices = new List<MyObject>();
var indexOf = 0;

lnkBack.NavigateUrl = allServices[indexOf - 1].FullURL;

Where I would think it would throw an index out of range exception, it throws an argument out of range exception. Why is this, when it's an index we're testing against?

I'd expect argument if it was something like the substring method where substring(-1) would be an argument?

like image 946
A-Bop Avatar asked Apr 04 '14 07:04

A-Bop


2 Answers

I assume that allServices is an array. Array inplenments IList<T> which throws an ArgumentOutOfRangeException instead of an IndexOutOfRangeException when you try to access an item at a negative index:

MSDN:

ArgumentOutOfRangeException: index is not a valid index in the IList<T>

You can reproduce it with this code:

IList<string> test = new string[]{ "0" };
string foo = test[-1];  // ArgumentOutOfRangeException

If you use it as string[] you get your expected IndexOutOfRangeException:

string[] test = new string[]{ "0" };
string foo = test[-1];  // IndexOutOfRangeException

Update: after your edit it's clear that allServices is a List<T> which implements also IList<T> as you can see in the documentation:

Implements IList<T>.Item

That's the reason why it throws the IndexOutOfRangeException of IList<T> instead of the ArgumentOutOfRangeException of array.

like image 182
Tim Schmelter Avatar answered Oct 24 '22 20:10

Tim Schmelter


Accessing the list as an array is just a syntax feature. What happens behind the scene is that the code uses the Item property, sending the index as the argument.

like image 33
Guffa Avatar answered Oct 24 '22 19:10

Guffa