JamesNK/Newtonsoft.Json · error · ArgumentOutOfRangeException
Index is equal to or greater than Count.
Error message
Index is equal to or greater than Count.
What it means
RemoveItemAt throws ArgumentOutOfRangeException when index >= ChildrenTokens.Count, i.e. the slot does not exist. The upper bound is Count-1.
Source
Thrown at Src/Newtonsoft.Json/Linq/JContainer.cs:423
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
#endif
return true;
}
internal virtual void RemoveItemAt(int index)
{
IList<JToken> children = ChildrenTokens;
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), "Index is less than 0.");
}
if (index >= children.Count)
{
throw new ArgumentOutOfRangeException(nameof(index), "Index is equal to or greater than Count.");
}
CheckReentrancy();
JToken item = children[index];
JToken? previous = (index == 0) ? null : children[index - 1];
JToken? next = (index == children.Count - 1) ? null : children[index + 1];
if (previous != null)
{
previous.Next = next;
}
if (next != null)
{
next.Previous = previous;
}
item.Parent = null;View on GitHub (pinned to 4f73e74372)
Solutions
- Loop backwards when removing, or recompute Count each iteration.
- Validate index < container.Count before calling RemoveAt.
- Prefer Remove(item) when removing by reference rather than by position.
Example fix
// before for (int i = 0; i < arr.Count; i++) arr.RemoveAt(i); // after for (int i = arr.Count - 1; i >= 0; i--) arr.RemoveAt(i);
Defensive patterns
Strategy: validation
Validate before calling
if (index >= arr.Count || index < 0) return; arr.RemoveAt(index);
Try / catch
try { arr.RemoveAt(index); }
catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "index") {
// index out of range; recompute and retry or skip
} Prevention
- Loop backwards when removing by index.
- Validate index < Count immediately before RemoveAt.
- Prefer Remove(item) for reference-based removal.
When it happens
Trigger: jArray.RemoveAt(jArray.Count); a stale/cached count larger than the live collection; loop variable overshooting.
Common situations: Iterating and removing in a forward loop without adjusting indices; cached Count after items were removed.
Related errors
- Index is less than 0.
- Index must be within the bounds of the List.
- arrayIndex is less than 0.
- arrayIndex is equal to or greater than the length of array.
- The number of elements in the source JObject is greater than
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/31c4c3a8e653ffd6.
Report an issue: GitHub.