Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange exception when using ConcurrentStack in C#

Tags:

c#

concurrency

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?

like image 261
TTT Avatar asked Sep 20 '11 14:09

TTT


3 Answers

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.

like image 196
Heinzi Avatar answered Oct 30 '22 13:10

Heinzi


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.

like image 2
nicholas.hauschild Avatar answered Oct 30 '22 14:10

nicholas.hauschild


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.

like image 2
Pete Montgomery Avatar answered Oct 30 '22 12:10

Pete Montgomery