dotnet/wpf · error · ArgumentException
SR.Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength
Error message
SR.Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength
What it means
PartialArray<T>.CopyTo throws ArgumentException wrapping Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength when arrayIndex >= destination array.Length. The starting offset must point inside the destination array.
Solutions
- Validate arrayIndex < array.Length before calling CopyTo.
- Recompute the offset from the current destination array each call.
- Ensure the destination array is allocated with length >= Count + arrayIndex.
Example fix
// before
partialArray.CopyTo(buffer, buffer.Length);
// after
if (buffer.Length > 0 && partialArray.Count <= buffer.Length)
partialArray.CopyTo(buffer, 0); Defensive patterns
Strategy: validation
Validate before calling
if (arrayIndex < 0 || arrayIndex >= array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
Type guard
bool IsValidCopyOffset(Array dest, int arrayIndex) => arrayIndex >= 0 && arrayIndex < dest.Length;
Try / catch
try { coll.CopyTo(dest, arrayIndex); }
catch (ArgumentException e) when (e.ParamName == "arrayIndex") { /* fix offset and retry */ } Prevention
- Assert arrayIndex is within [0, array.Length-1] before CopyTo.
- Recompute offsets after any destination reallocation.
- Reserve at least one slot: destination length must exceed arrayIndex.
When it happens
Trigger: Calling CopyTo(array, arrayIndex) where arrayIndex equals or exceeds array.Length, e.g. CopyTo(arr, arr.Length) or a stale offset after the destination was reallocated smaller.
Common situations: Cursor-based copy loops that increment arrayIndex without rechecking the destination length, or reuse of an offset computed for a different, larger array.
Related errors
- Cannot pass multidimensional array to the CopyTo method on…
- SR.Collection_BadDestArray
- SR.Collection_BadDestArray
- SR.Collection_BadDestArray
- SR.Collection_BadDestArray
AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14).
Data as JSON: /api/errors/b4fdfad83935f376.
Report an issue: GitHub.
Appendix: source
Thrown at src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/PartialArray.cs:137
}
public void CopyTo(T[] array, int arrayIndex)
{
// parameter validations
ArgumentNullException.ThrowIfNull(array);
if (array.Rank != 1)
{
throw new ArgumentException(
SR.Collection_CopyTo_ArrayCannotBeMultidimensional,
nameof(array));
}
ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex);
if (arrayIndex >= array.Length)
{
throw new ArgumentException(
SR.Format(
SR.Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength,
"arrayIndex",
"array"),
nameof(arrayIndex));
}
if ((array.Length - Count - arrayIndex) < 0)
{
throw new ArgumentException(
SR.Format(
SR.Collection_CopyTo_NumberOfElementsExceedsArrayLength,
"arrayIndex",
"array"));
}
// do the copying hereView on GitHub (pinned to 81131a70a4)