JamesNK/Newtonsoft.Json · error · ArgumentNullException
array
Error message
array
What it means
CopyItemsTo (which backs CopyTo) throws ArgumentNullException named 'array' when the destination array is null. The null-array guard runs before any bounds checks.
Source
Thrown at Src/Newtonsoft.Json/Linq/JContainer.cs:593
if (existing == null || existing.Parent != this)
{
return;
}
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);View on GitHub (pinned to 4f73e74372)
Solutions
- Allocate the destination array before copying: new JToken[container.Count].
- Null-check the array argument at the call site and fail with a clear message.
- Use the ToList()/LINQ materialization if you just need a snapshot.
Example fix
// before arr.CopyTo(null, 0); // after var dest = new JToken[arr.Count]; arr.CopyTo(dest, 0);
Defensive patterns
Strategy: validation
Validate before calling
var dest = array ?? new JToken[container.Count]; container.CopyTo(dest, 0);
Try / catch
try { container.CopyTo(dest, arrayIndex); }
catch (ArgumentNullException ex) when (ex.ParamName == "array") {
dest = new JToken[container.Count];
container.CopyTo(dest, 0);
} Prevention
- Allocate the destination array before calling CopyTo.
- Null-check array arguments at the call site.
- Use ToList() for a quick snapshot when you don't need an array.
When it happens
Trigger: jArray.CopyTo(null, 0); ((ICollection)container).CopyTo(null, 0); passing a null array variable.
Common situations: Uninitialized destination array; generic collection-copy helper that forwards a null.
Related errors
- 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
- Index must be within the bounds of the List.
- Index is less than 0.
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/0477cdf2a5e7fa17.
Report an issue: GitHub.