AvaloniaUI/Avalonia · error · ArgumentNullException

Value cannot be null. (Parameter 'array')

Error message

Value cannot be null. (Parameter 'array')

What it means

CompositeDisposable.CopyTo(array, arrayIndex) copies contained disposables into a target array and throws ArgumentNullException(nameof(array)) when array is null, before any index check. Standard ICollection<T> contract.

Source

Thrown at src/Avalonia.Base/Reactive/CompositeDisposable.cs:296

                return false;
            }

            return _disposables.Contains(item);
        }
    }

    /// <summary>
    /// Copies the disposables contained in the <see cref="CompositeDisposable"/> to an array, starting at a particular array index.
    /// </summary>
    /// <param name="array">Array to copy the contained disposables to.</param>
    /// <param name="arrayIndex">Target index at which to copy the first disposable of the group.</param>
    /// <exception cref="ArgumentNullException"><paramref name="array"/> is <c>null</c>.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than zero. -or - <paramref name="arrayIndex"/> is larger than or equal to the array length.</exception>
    public void CopyTo(IDisposable[] array, int arrayIndex)
    {
        if (array == null)
        {
            throw new ArgumentNullException(nameof(array));
        }

        if (arrayIndex < 0 || arrayIndex >= array.Length)
        {
            throw new ArgumentOutOfRangeException(nameof(arrayIndex));
        }

        lock (_gate)
        {
            // disposed composites are always empty
            if (_disposed)
            {
                return;
            }

            if (arrayIndex + _count > array.Length)
            {
                // there is not enough space beyond arrayIndex 

View on GitHub (pinned to 11c5427268)

Solutions

  1. Allocate the target array before CopyTo: var arr = new IDisposable[composite.Count];.
  2. Null-check and branch if the array is optional.
  3. Use composite.ToArray()-equivalent helpers where the framework provides them.

Example fix

// before
IDisposable[] arr = null;
composite.CopyTo(arr, 0);

// after
var arr = new IDisposable[composite.Count];
composite.CopyTo(arr, 0);
Defensive patterns

Strategy: validation

Validate before calling

var arr = new IDisposable[composite.Count];
composite.CopyTo(arr, 0);

Type guard

bool NotNull(IDisposable[]? a) => a is not null;

Prevention

When it happens

Trigger: Calling composite.CopyTo(null, 0) or passing a null IDisposable[] variable.

Common situations: Allocating the destination array conditionally and leaving it null on some path, then unconditionally calling CopyTo.

Related errors


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