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

  1. Validate 0 <= arrayIndex <= array.Length before calling CopyTo.
  2. Use arrayIndex = 0 (or list.CopyTo(array)) for full-collection copies.
  3. 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

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


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)