Strange exception when using ConcurrentStack in C#
I have this C# code, it throws an ArgumentOutOfRangeException
, I wonder why?
ConcurrentStack<int> intsStack = new ConcurrentStack<int>();
int[] myInts = new int[0];
intsStack.PushRange(myInts);
The Message
property of the ArgumentOutOfRangeException
error:
The startIndex argument must be greater than or equal to zero.
Parameter name: startIndex
The array is empty but not null
, I didn't expect 开发者_如何学运维any exception at all, just that nothing was added to the stack. Is this a reasonable exception or not?
From an implementation perspective, it's reasonable if you look at the definition of the PushRange(T[], int, int) overload:
ArgumentOutOfRangeException: startIndex or count is negative. Or startIndex is greater than or equal to the length of items.
The length of your array is zero. Therefore, there is no possible valid value for startIndex.
From a documentation perspective, it's not reasonable, because the documentation of the PushRange(T[]) overload does not mention the ArgumentOutOfRangeException
.
If the array is empty, it has no index 0, which is what it is complaining about.
With a zero based index, 0 is the first index, pointing to the first item. So it is actually complaining that there is nothing in the array.
The argument to AddRange is an empty array, so you are trying to push zero items on to the stack. So it's a very reasonable exception.
EDIT: But you're right, it's a bad exception message. You can guess that it is because internally the overload PushRange(T[], Int32, Int32) is actually throwing the exception.
精彩评论