AvaloniaUI/Avalonia · error · ArgumentException

Invalid index.

Error message

Invalid index.

What it means

ArgumentException thrown by AvaloniaList.ICollection.CopyTo when the starting index is negative. The destination array index must be a valid non-negative offset where copying begins.

Source

Thrown at src/Avalonia.Base/Collections/AvaloniaList.cs:676

        {
            if (array == null)
            {
                throw new ArgumentNullException(nameof(array));
            }

            if (array.Rank != 1)
            {
                throw new ArgumentException("Multi-dimensional arrays are not supported.");
            }

            if (array.GetLowerBound(0) != 0)
            {
                throw new ArgumentException("Non-zero lower bounds are not supported.");
            }

            if (index < 0)
            {
                throw new ArgumentException("Invalid index.");
            }

            if (array.Length - index < Count)
            {
                throw new ArgumentException("The target array is too small.");
            }

            if (array is T[] tArray)
            {
                _inner.CopyTo(tArray, index);
            }
            else
            {
                //
                // Catch the obvious case assignment will fail.
                // We can't find all possible problems by doing the check though.
                // For example, if the element type of the Array is derived from T,
                // we can't figure out if we can successfully copy the element beforehand.

View on GitHub (pinned to 11c5427268)

Solutions

  1. Pass a non-negative index (typically 0) into the destination array.
  2. Validate/clamp the index before calling CopyTo.
  3. Review the computation producing the index for underflow bugs.

Example fix

// before
((ICollection)list).CopyTo(arr, offset - 1);

// after
var idx = Math.Max(0, offset);
((ICollection)list).CopyTo(arr, idx);
Defensive patterns

Strategy: validation

Validate before calling

if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, "Index must be non-negative.");

Prevention

When it happens

Trigger: Calling ((ICollection)list).CopyTo(array, -1) or passing a computed index that underflows to a negative value.

Common situations: An off-by-one or subtraction that yields a negative index; a default int parameter left at -1 as a sentinel and forwarded unchecked.

Related errors


AI-assisted analysis of AvaloniaUI/Avalonia@11c5427268 (2026-08-13). Data as JSON: /api/errors/ddce2aaa6ad8126d. Report an issue: GitHub.