bchavez/Bogus · error · ArgumentException

The list is empty. There are no items to select.

Error message

The list is empty. There are no items to select.

What it means

Thrown by Randomizer.ListItem<T>(IList<T>) when list.Count <= 0. Requires at least one element to pick from. The param is named 'list'.

Source

Thrown at Source/Bogus/Randomizer.cs:534

      return Shuffle(array).Take(count.Value).ToArray();
   }

   /// <summary>
   /// Get a random list item.
   /// </summary>
   public T ListItem<T>(List<T> list)
   {
      return ListItem(list as IList<T>);
   }

   /// <summary>
   /// Get a random list item.
   /// </summary>
   public T ListItem<T>(IList<T> list)
   {
      if (list.Count <= 0)
         throw new ArgumentException("The list is empty. There are no items to select.", nameof(list));

      var r = Number(max: list.Count - 1);
      return list[r];
   }

   /// <summary>
   /// Get a random subset of a List.
   /// </summary>
   /// <param name="items">The source of items to pick from.</param>
   /// <param name="count">The number of items to pick; otherwise, a random amount is picked.</param>
   public List<T> ListItems<T>(IList<T> items, int? count = null)
   {
      if( count > items.Count )
         throw new ArgumentOutOfRangeException(nameof(count));
      if( count is null )
         count = Number(0, items.Count - 1);

      return Shuffle(items).Take(count.Value).ToList();

View on GitHub (pinned to 6ece18c5c2)

Solutions

  1. Verify list.Count > 0 before calling ListItem.
  2. Ensure the source collection is populated upstream.
  3. Provide a fallback when the list is empty.

Example fix

// before
var item = f.Random.ListItem(filtered.ToList());
// after
var list = filtered.ToList();
var item = list.Count > 0 ? f.Random.ListItem(list) : defaultItem;
Defensive patterns

Strategy: validation

Validate before calling

static T SafeListItem<T>(Bogus.Randomizer r, IList<T> list, T fallback) {
    return list.Count > 0 ? r.ListItem(list) : fallback;
}

Type guard

bool HasItems<T>(IList<T> list) => list.Count > 0;

Try / catch

try { return r.ListItem(list); }
catch (ArgumentException ex) when (ex.Message.Contains("list is empty")) {
    return default;
}

Prevention

When it happens

Trigger: Calling f.Random.ListItem(new List<T>()) or passing an empty IList from a query result.

Common situations: Empty results from a filtered LINQ query passed directly to ListItem; collection not yet populated at call time.

Related errors


AI-assisted analysis of bchavez/Bogus@6ece18c5c2 (2026-08-13). Data as JSON: /api/errors/d31a88656f02b3ca. Report an issue: GitHub.