Pergunta

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?

Foi útil?

Solução

Arrays and list both inplement 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

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

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top