Skip to content

Incorrect exception message and type produced by CopyTo method from ICollection and ICollection<> in Dictionary<TKey, TValue> #131782

Description

@Enderlook

Description

The method ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[], int) from Dictionary<TKey, TValue> seems to produce an incorrect exception message in some situations, telling that a non-negative index is required when that is not exactly the error that was produced.

Reproduction Steps

using System.Collections.Generic;

Dictionary<int, int> actual = new();
KeyValuePair<int, int>[] array = new KeyValuePair<int, int>[0];
((ICollection<KeyValuePair<int, int>>)actual).CopyTo(array, array.Length + 1);

The same also happens if the dictionary isn't empty or the array has some length.
It also happens with non-generic ICollection method.

Expected behavior

System.ArgumentException: The number of elements in the source is greater than the available space from index to the end of the destination array. (Parameter 'index') (According to documentation)

Actual behavior

System.ArgumentOutOfRangeException: Non-negative number required. (Parameter 'index')

Regression?

No response

Known Workarounds

Add an early check in my code.

Configuration

Sharplab default produces the error.
I also found it in .NET 10, Windows 11 x64.

Other information

If tweaking the behaviour this is a breaking change, then maybe the documentation should be aligned with the current behaviour.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions