JamesNK/Newtonsoft.Json · error · ArgumentOutOfRangeException
arrayIndex is less than 0.
Error message
arrayIndex is less than 0.
What it means
CopyItemsTo throws ArgumentOutOfRangeException when arrayIndex is negative. The destination offset must be a valid non-negative position in the target array.
Source
Thrown at Src/Newtonsoft.Json/Linq/JContainer.cs:597
int index = IndexOfItem(existing);
SetItem(index, replacement);
}
internal virtual bool ContainsItem(JToken? item)
{
return (IndexOfItem(item) != -1);
}
internal virtual void CopyItemsTo(Array array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), "arrayIndex is less than 0.");
}
if (arrayIndex >= array.Length && arrayIndex != 0)
{
throw new ArgumentException("arrayIndex is equal to or greater than the length of array.");
}
if (Count > array.Length - arrayIndex)
{
throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
}
int index = 0;
foreach (JToken token in ChildrenTokens)
{
array.SetValue(token, arrayIndex + index);
index++;
}
}
View on GitHub (pinned to 4f73e74372)
Solutions
- Validate arrayIndex >= 0 before calling CopyTo.
- Use 0 when you want to copy from the start.
- Clamp computed offsets to a minimum of 0.
Example fix
// before arr.CopyTo(dest, offset - 1); // after arr.CopyTo(dest, Math.Max(0, offset - 1));
Defensive patterns
Strategy: validation
Validate before calling
if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); container.CopyTo(dest, arrayIndex);
Try / catch
try { container.CopyTo(dest, arrayIndex); }
catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "arrayIndex") {
container.CopyTo(dest, 0);
} Prevention
- Validate arrayIndex >= 0 before CopyTo.
- Use 0 to copy from the start.
- Clamp computed offsets to at least 0.
When it happens
Trigger: jArray.CopyTo(arr, -1); a computed offset that underflows below zero.
Common situations: Off-by-one arithmetic on the offset; passing an index derived from an unfound position.
Related errors
- arrayIndex is equal to or greater than the length of array.
- The number of elements in the source JObject is greater than
- Index must be within the bounds of the List.
- Index is less than 0.
- Index is equal to or greater than Count.
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/9954bc139e45903a.
Report an issue: GitHub.