bchavez/Bogus · error · ArgumentException
The array is empty. There are no items to select.
Error message
The array is empty. There are no items to select.
What it means
Thrown by Randomizer.ArrayElement<T> when the supplied array has Length <= 0. The method picks a random index, so it requires at least one element. The param is named 'array'.
Source
Thrown at Source/Bogus/Randomizer.cs:478
return Number() == 0;
}
/// <summary>
/// Get a random boolean.
/// </summary>
/// <param name="weight">The probability of true. Ranges from 0 to 1.</param>
public bool Bool(float weight)
{
return Float() < weight;
}
/// <summary>
/// Get a random array element.
/// </summary>
public T ArrayElement<T>(T[] array)
{
if (array.Length <= 0)
throw new ArgumentException("The array is empty. There are no items to select.", nameof(array));
var r = Number(max: array.Length - 1);
return array[r];
}
/// <summary>
/// Helper method to get a random element in a BSON array.
/// </summary>
public BValue ArrayElement(BArray props, int? min = null, int? max = null)
{
var r = Number(min: min ?? 0, max: max - 1 ?? props.Count - 1);
return props[r];
}
/// <summary>
/// Get a random array element.
/// </summary>
public string ArrayElement(Array array)View on GitHub (pinned to 6ece18c5c2)
Solutions
- Check array.Length > 0 before calling ArrayElement.
- Provide a non-empty default/fallback array.
- Guard the upstream filter so empty results are handled earlier.
Example fix
// before var pick = f.Random.ArrayElement(items.Where(x => x.Rare).ToArray()); // after var rare = items.Where(x => x.Rare).ToArray(); var pick = rare.Length > 0 ? f.Random.ArrayElement(rare) : fallbackItem;
Defensive patterns
Strategy: validation
Validate before calling
static T SafeArrayElement<T>(Bogus.Randomizer r, T[] arr, T fallback) {
return arr.Length > 0 ? r.ArrayElement(arr) : fallback;
} Type guard
bool HasItems<T>(T[] arr) => arr is { Length: > 0 }; Try / catch
try { return r.ArrayElement(arr); }
catch (ArgumentException ex) when (ex.Message.Contains("array is empty")) {
return default; // or fallback element
} Prevention
- Check array.Length before sampling.
- Provide fallback elements for empty sources.
- Guard upstream LINQ filters that can return empty arrays.
When it happens
Trigger: Calling f.Random.ArrayElement(Array.Empty<T>()) or passing a zero-length array from a filtered/empty source.
Common situations: Filtering a source array to empty then sampling; results of a LINQ Where().ToArray() that yields nothing.
Related errors
- The list is empty. There are no items to select.
- The collection is empty. There are no items to select.
- max digit can't be lager than 9 or smaller than 0
- The min/max range is invalid. The minimum value '{min}' is g
- The specified range does not contain any even numbers.
AI-assisted analysis of bchavez/Bogus@6ece18c5c2 (2026-08-13).
Data as JSON: /api/errors/8fb0f397735b2d86.
Report an issue: GitHub.