First of all, if someone should take care of an invalid input it's the runtime and not the compiler since the input is of the same valid type (int
).
With that said, actually, seeing the source code of IndexOf
making it seem like an implementation bug:
[__DynamicallyInvokable]
public int IndexOf(T item, int index)
{
if (index > this._size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
}
return Array.IndexOf<T>(this._items, item, index, this._size - index);
}
As you can see, it was intended to not allow you to insert an invalid index which is bigger than the size of the list, but the comparison is done with >
instead of >=
.
The following code returns 0
:
var list = new List<int>() { 100 };
Console.WriteLine(list.IndexOf(100/*item*/, 0/*start index*/));
The following code returns -1
:
var list = new List<int>() { 100 };
Console.WriteLine(list.IndexOf(100/*item*/, 1/*start index*/));
While The following code throws an Exception
:
var list = new List<int>() { 100 };
Console.WriteLine(list.IndexOf(100/*item*/, 2/*start index*/));
There is no reason what so ever for the second and third cases to behave differently which makes it seem as a bug in the implementation of IndexOf
.
Also, the documentation says:
ArgumentOutOfRangeException | index is outside the range of valid indexes for the List<T>
.
Which as we have just seen is not what happening.
Note: the same behaviour happens with arrays:
int[] arr = { 100 };
//Output: 0
Console.WriteLine(Array.IndexOf(arr, 100/*item*/, 0/*start index*/));
//Output: -1
Console.WriteLine(Array.IndexOf(arr, 100/*item*/, 1/*start index*/));
//Throws ArgumentOutOfRangeException
Console.WriteLine(Array.IndexOf(arr, 100/*item*/, 2/*start index*/));