litedb-org/LiteDB · error · ArgumentNullException
Value cannot be null. (Parameter 'collection')
Error message
Value cannot be null. (Parameter 'collection')
What it means
Thrown by BsonArray.AddRange<TCollection> when the collection argument is null. The method pre-sizes the backing list based on collection.Count and then enumerates, so a null collection cannot be measured or iterated. The guard prevents both a NullReferenceException and a malformed capacity calculation.
Source
Thrown at LiteDB/Document/BsonArray.cs:72
return this.RawValue[index];
}
set
{
this.RawValue[index] = value ?? BsonValue.Null;
}
}
public int Count => this.RawValue.Count;
public bool IsReadOnly => false;
public void Add(BsonValue item) => this.RawValue.Add(item ?? BsonValue.Null);
public void AddRange<TCollection>(TCollection collection)
where TCollection : ICollection<BsonValue>
{
if(collection == null)
throw new ArgumentNullException(nameof(collection));
var list = (List<BsonValue>)base.RawValue;
var listEmptySpace = list.Capacity - list.Count;
if (listEmptySpace < collection.Count)
{
list.Capacity += collection.Count;
}
foreach (var bsonValue in collection)
{
list.Add(bsonValue ?? Null);
}
}
public void AddRange(IEnumerable<BsonValue> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));View on GitHub (pinned to f906a5f850)
Solutions
- Null-check the collection before AddRange; skip the call if null is acceptable.
- Coalesce to an empty collection at the source.
- Ensure collection-producing methods never return null.
Example fix
// before
arr.AddRange(extraValues);
// after
if (extraValues is not null)
arr.AddRange(extraValues); Defensive patterns
Strategy: validation
Validate before calling
if (collection is not null)
arr.AddRange(collection); Type guard
static bool IsNonNullCollection<T>(ICollection<T> c) => c is not null;
Prevention
- Guard AddRange calls with a null check.
- Coalesce optional sub-collections to empty at the source.
- Ensure collection-producing methods never return null.
When it happens
Trigger: Calling array.AddRange((List<BsonValue>)null); passing a collection from a query/lookup that returned null; feeding a nullable ICollection<BsonValue> field.
Common situations: Appending optional sub-collections into an existing BsonArray; merging results from conditional lookups; refactoring that left a collection uninitialized.
Related errors
- Value cannot be null. (Parameter 'array')
- Value cannot be null. (Parameter 'items')
- Value cannot be null. (Parameter 'collection')
- Value cannot be null. (Parameter 'doc')
- Value cannot be null. (Parameter 'buffer')
AI-assisted analysis of litedb-org/LiteDB@f906a5f850 (2026-08-13).
Data as JSON: /api/errors/7d08e0f49693953e.
Report an issue: GitHub.