dotnetcore/CAP · error · ArgumentOutOfRangeException

Specified argument was out of the range of valid values…

Error message

Specified argument was out of the range of valid values. (Parameter 'arrayIndex')

What it means

CircularBuffer<T>.CopyTo throws ArgumentOutOfRangeException("arrayIndex") when the starting offset is negative. The buffer requires a non-negative index into the destination array. A negative offset means caller index arithmetic went wrong before the copy.

Solutions

  1. Validate offset >= 0 before calling CopyTo (Math.Max(0, offset) if clamping is acceptable).
  2. Fix the index computation that produced the negative value.
  3. If the offset comes from external input, parse and range-check it explicitly.

Example fix

// before
int offset = current - capacity;
buffer.CopyTo(array, offset);
// after
int offset = Math.Max(0, current - capacity);
if (offset >= 0) buffer.CopyTo(array, offset);
Defensive patterns

Strategy: validation

Validate before calling

if (offset < 0) throw new InvalidOperationException("offset must be >= 0");
buffer.CopyTo(array, offset);

Try / catch

try { buffer.CopyTo(array, offset); }
catch (ArgumentOutOfRangeException) { /* clamp or log invalid offset */ }

Prevention

When it happens

Trigger: Calling CopyTo(array, index) with index < 0, e.g. an unvalidated caller-supplied offset or an underflowing computation like (size - capacity) used as the offset.

Common situations: Off-by-one/underflow in code computing a write position, user input parsed into an int offset without validation, or int subtraction wrapping below zero.

Related errors


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

Appendix: source

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

        _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)