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?
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 theIList<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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With