Skip to content

List<T>.IndexOf outputs incorrect error message #67423

@HeinziAT

Description

@HeinziAT

Description

The error message returned by List<T>.IndexOf if an invalid index is used is incorrect. As it is currently implemented, the size of the collection (2 in the repro example below) is a valid input for index.

Reproduction Steps

// list of length 2
var list = new List<string>() { "a", "b" };

Console.WriteLine(list.IndexOf("a", 2)); // yields -1
Console.WriteLine(list.IndexOf("a", 3)); // yields an error

(fiddle)

Expected behavior

An ArgumentException with the following error text is thrown:

Index was out of range. Must be non-negative and less than or equal to the size of the collection. (Parameter 'index')

(Alternatively: Must be non-negative and not greater than the size of the collection.)

Actual behavior

An ArgumentException with the following error text is thrown:

Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')

Regression?

No response

Known Workarounds

No response

Configuration

Tested with dotnetfiddle, with all currently available compilers (.NET 4.7.2, Roslyn 4.0, .NET 6).

Other information

I do not suggest to change the behavior of IndexOf - the current behavior is the only sane and consistent one. However, the error message (and the documentation of List<T>.IndexOf) should be updated to reflect the actual behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.CollectionsenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions