AvaloniaUI/Avalonia · error · ArgumentNullException

array

Error message

array

What it means

ArgumentNullException("array") from PooledList<T>.ICollection.CopyTo(Array, int) when the target array is null. The guard `_ = array ?? throw` runs before the rank check and Array.Copy, so a null destination array fails fast. It mirrors the standard ICollection.CopyTo contract.

Source

Thrown at src/Avalonia.Base/Collections/Pooled/PooledList.cs:661

        /// </summary>
        public void CopyTo(Span<T> span)
        {
            if (span.Length < Count)
                throw new ArgumentException("Destination span is shorter than the list to be copied.");

            Span.CopyTo(span);
        }

        void ICollection<T>.CopyTo(T[] array, int arrayIndex)
        {
            Array.Copy(_items, 0, array, arrayIndex, _size);
        }

        // Copies this List into array, which must be of a 
        // compatible array type.  
        void ICollection.CopyTo(Array array, int arrayIndex)
        {
            _ = array ?? throw new ArgumentNullException(nameof(array));

            if (array.Rank != 1)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
            }

            try
            {
                Array.Copy(_items, 0, array, arrayIndex, _size);
            }
            catch (ArrayTypeMismatchException)
            {
                ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
            }
        }

        /// <summary>
        /// Ensures that the capacity of this list is at least the given minimum

View on GitHub (pinned to 11c5427268)

Solutions

  1. Allocate the destination array before calling: `var arr = new T[list.Count]; ((ICollection)list).CopyTo(arr, 0);`.
  2. Prefer the strongly-typed CopyTo(T[], int) overload or CopyTo(Span<T>) which make intent explicit.
  3. Null-check the array parameter in your own code before forwarding it.

Example fix

// before
T[] arr = null;
((ICollection)list).CopyTo(arr, 0);

// after
T[] arr = new T[list.Count];
((ICollection)list).CopyTo(arr, 0);
Defensive patterns

Strategy: validation

Validate before calling

if (array is null) throw new ArgumentNullException(nameof(array));
((ICollection)list).CopyTo(array, index);

Type guard

static bool IsUsable(Array a) => a is not null && a.Rank == 1;

Prevention

When it happens

Trigger: Invoking the non-generic CopyTo with a null array: `((ICollection)list).CopyTo(null!, 0)`, or passing an uninitialized array variable.

Common situations: Passing a null array from an uninitialized local; LINQ/collection-init paths that hand a null Array through; generic code forwarding a possibly-null array parameter.

Related errors


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