dotnetcore/CAP · error · ArgumentNullException

Value cannot be null. (Parameter 'array')

Error message

Value cannot be null. (Parameter 'array')

What it means

CircularBuffer<T>.CopyTo validates its arguments and throws ArgumentNullException("Value cannot be null. (Parameter 'array')") when the destination array is null. This is a standard guard before copying buffer contents into the array. Reaching it usually means the caller computed a null destination, e.g. ToArray-like code on an empty/incorrectly sized buffer.

Solutions

  1. Ensure the destination array is allocated with new T[Count] (or larger) before calling CopyTo.
  2. Add a null/empty check at the call site and skip the copy when there is nothing to copy.
  3. If a helper (ToArray) produced null, fix it to return Array.Empty<T>() for empty buffers.

Example fix

// before
T[] result = GetDestination(); // may be null
buffer.CopyTo(result, 0);
// after
T[] result = GetDestination() ?? new T[buffer.Count];
buffer.CopyTo(result, 0);
Defensive patterns

Strategy: validation

Validate before calling

if (dest == null) dest = new T[buffer.Count];
buffer.CopyTo(dest, 0);

Try / catch

try { buffer.CopyTo(dest, 0); }
catch (ArgumentNullException) { dest = new T[buffer.Count]; buffer.CopyTo(dest, 0); }

Prevention

When it happens

Trigger: Passing null as the array argument to CopyTo, e.g. buffer.CopyTo(null, 0), or an indirect call from helper code (ToArray) that allocates the destination incorrectly.

Common situations: A factory or cache returning a null array on failure, uninitialized fields meant to hold the destination buffer, or deserialization yielding null before CopyTo is called.

Related errors


AI-assisted analysis of dotnetcore/CAP@e52b8508e5 (2026-09-14). Data as JSON: /api/errors/bcb9e17820d9cfb9. Report an issue: GitHub.

Appendix: source

Thrown at src/DotNetCore.CAP.Dashboard/CircularBuffer.cs:160

        }

        _items[itemIndex] = item;
    }

    public void Clear()
    {
        _firstIndex = 0;
        Count = 0;
    }

    public bool Contains(T item)
    {
        throw new NotImplementedException();
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        if (array == null) throw new ArgumentNullException(nameof(array));

        if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex));

        if (Count > array.Length - arrayIndex) throw new ArgumentException("arrayIndex");

        // Iterate through the buffer in correct order.
        foreach (var item in this)
        {
            array[arrayIndex++] = item;
        }
    }

    public bool Remove(T item)
    {
        throw new NotImplementedException();
    }

    #endregion

View on GitHub (pinned to e52b8508e5)