bchavez/Bogus · error · ArgumentOutOfRangeException

{nameof(amountToPick)} needs to be a positive integer.

Error message

{nameof(amountToPick)} needs to be a positive integer.

What it means

Faker.PickRandom(items, amountToPick) rejects a negative amountToPick with ArgumentOutOfRangeException. Note the check is '< 0', so zero is accepted (and yields an empty result) even though the message says 'positive integer' - the wording is looser than the actual guard.

Source

Thrown at Source/Bogus/Faker.cs:293

   /// <summary>
   /// Picks a random item of T specified in the parameter list.
   /// </summary>
   public T PickRandomParam<T>(params T[] items)
   {
      return this.Random.ArrayElement(items);
   }

   /// <summary>
   /// Helper to pick random subset of elements out of the list.
   /// </summary>
   /// <param name="amountToPick">amount of elements to pick of the list.</param>
   /// <exception cref="ArgumentException">if amountToPick is lower than zero.</exception>
   public IEnumerable<T> PickRandom<T>(IEnumerable<T> items, int amountToPick)
   {
      if( amountToPick < 0 )
      {
         throw new ArgumentOutOfRangeException($"{nameof(amountToPick)} needs to be a positive integer.");
      }
      var size = items.Count();
      if( amountToPick > size )
      {
         throw new ArgumentOutOfRangeException($"{nameof(amountToPick)} is greater than the number of items.");
      }
      return this.Random.Shuffle(items).Take(amountToPick);
   }

   /// <summary>
   /// Helper method to call faker actions multiple times and return the result as IList of T
   /// </summary>
   public IList<T> Make<T>(int count, Func<T> action)
   {
      return Enumerable.Range(1, count).Select(n => action()).ToList();
   }

   /// <summary>

View on GitHub (pinned to 6ece18c5c2)

Solutions

  1. Clamp amountToPick to a non-negative value before calling.
  2. Validate the upstream input and reject negatives early with a clear error.
  3. Remember 0 is allowed and returns an empty enumerable.

Example fix

// before
var subset = f.PickRandom(items, requestedCount);

// after
var subset = f.PickRandom(items, Math.Max(0, requestedCount));
Defensive patterns

Strategy: validation

Validate before calling

int amountToPick = Math.Max(0, requestedCount);
var subset = f.PickRandom(items, amountToPick);

Prevention

When it happens

Trigger: Calling f.PickRandom(items, -1) or passing a negative count derived from user input or a calculation that underflows.

Common situations: Passing an unvalidated user-supplied count, or computing amountToPick as (desired - offset) where offset exceeds desired.

Related errors


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