dotnet/wpf · error · ArgumentException
arrayIndex
Error message
arrayIndex
What it means
CopyTo throws ArgumentException("arrayIndex") when arrayIndex is negative or greater than the target array's length. ArgumentOutOfRangeException.ThrowIfNegative handles the negative case; the explicit check handles arrayIndex > array.Length. Either leaves no valid contiguous region to write into.
Solutions
- Validate 0 <= arrayIndex <= array.Length before calling CopyTo.
- Use arrayIndex = 0 (or list.CopyTo(array)) for full-collection copies.
- Clamp: arrayIndex = Math.Clamp(arrayIndex, 0, array.Length).
Example fix
// before list.CopyTo(arr, -1); // after int start = Math.Max(0, Math.Min(offset, arr.Length)); list.CopyTo(arr, start);
Defensive patterns
Strategy: validation
Validate before calling
if (arrayIndex < 0 || arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
Prevention
- Clamp offsets to [0, array.Length]
- Default to arrayIndex 0 for full copies
- Never pass sentinel values like -1 as offsets
When it happens
Trigger: Calling CopyTo(array, arrayIndex) with arrayIndex < 0 or arrayIndex > array.Length (arrayIndex == array.Length is allowed by this check but then fails the capacity check unless count == 0).
Common situations: Off-by-one arithmetic producing index == Length + 1; passing an uninitialized sentinel value (-1) as the offset; resuming a copy into a resized array with a stale offset.
Related errors
- SR.ArgumentOutOfRange_NeedNonNegNum
- SR.Format(SR.Collection_CopyTo_IndexGreaterThanOrEqualToArra…
- args
- args
- ArgumentOutOfRangeException(authenticationType)
AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14).
Data as JSON: /api/errors/aff17835e5dfcb0c.
Report an issue: GitHub.
Appendix: source
Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextElementCollection.cs:609
#region ICollection Members
void ICollection.CopyTo(Array array, int arrayIndex)
{
int count = this.Count;
ArgumentNullException.ThrowIfNull(array);
Type elementType = array.GetType().GetElementType();
if (elementType == null || !elementType.IsAssignableFrom(typeof(TextElementType)))
{
throw new ArgumentException("array");
}
ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex);
if (arrayIndex > array.Length)
{
throw new ArgumentException("arrayIndex");
}
if (array.Length < arrayIndex + count)
{
throw new ArgumentException(SR.Format(SR.TextElementCollection_CannotCopyToArrayNotSufficientMemory, count, arrayIndex, array.Length));
}
for (TextElementType element = (TextElementType)this.FirstChild; element != null; element = (TextElementType)element.NextElement)
{
array.SetValue(element, arrayIndex++);
}
}
int ICollection.Count
{
get
{
return this.Count;View on GitHub (pinned to 81131a70a4)