runtime icon indicating copy to clipboard operation
runtime copied to clipboard

ImmutableArray<T>.IndexOf throws ArgumentOutOfRangeException when startIndex equals Length and count is 0

Open prozolic opened this issue 9 months ago • 1 comments

Description

In ImmutableArray<T>.IndexOf, the upper bound guard for startIndex is startIndex < self.Length, whereas Array.IndexOf is implemented with startIndex <= array.Length. https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Array.cs#L1904-L1907

As a result, when startIndex == ImmutableArray.Length and count == 0, Array.IndexOf returns -1, but ImmutableArray<T>.IndexOf throws an ArgumentOutOfRangeException.

Reproduction Steps

int[] array = [1, 2, 3, 4];
var index = Array.IndexOf(array, 2, 4, 0); // Return -1

var immutableArray = ImmutableArray.Create(1, 2, 3, 4);
var index = immutableArray.IndexOf(2, 4, 0); // throw ArgumentOutOfRangeException (should return -1)

Expected behavior

-1 is returned.

Actual behavior

ArgumentOutOfRangeException is thrown.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

When we investigated #70950, I noticed this issue. Additionally, ImmutableList<T>.IndexOf also had issues such as a missing upper bound guard, so a PR addressing these together has been submitted at #124967.

prozolic avatar Feb 27 '26 14:02 prozolic

Tagging subscribers to this area: @dotnet/area-system-collections See info in area-owners.md if you want to be subscribed.

dotnet-policy-service avatar Feb 27 '26 14:02 dotnet-policy-service