bchavez/Bogus · error · ArgumentOutOfRangeException

{nameof(items)}.Length and {nameof(weights)}.Length must be

Error message

{nameof(items)}.Length and {nameof(weights)}.Length must be the same.

What it means

Thrown by Randomizer.WeightedRandom when weights.Length != items.Length. Weighted sampling pairs each item with a weight by index, so the two arrays must be the same length. Note: the message references both Lengths but throws ArgumentOutOfRangeException.

Source

Thrown at Source/Bogus/Randomizer.cs:847

   /// <summary>
   /// Generates a random hexadecimal string.
   /// </summary>
   public string Hexadecimal(int length = 1, string prefix = "0x")
   {
      var sb = new StringBuilder();
      return Enumerable.Range(1, length).Aggregate(sb, (b, i) => b.Append(ArrayElement(HexChars)), b => $"{prefix}{b}");
   }

   //items are weighted by the decimal probability in their value
   /// <summary>
   /// Returns a selection of T[] based on a weighted distribution of probability.
   /// </summary>
   /// <param name="items">Items to draw the selection from.</param>
   /// <param name="weights">Weights in decimal form: IE:[.25, .50, .25] for total of 3 items. Should add up to 1.</param>
   public T WeightedRandom<T>(T[] items, float[] weights)
   {
      if( weights.Length != items.Length ) throw new ArgumentOutOfRangeException($"{nameof(items)}.Length and {nameof(weights)}.Length must be the same.");

      var rand = this.Float();
      float max;
      float min = 0f;

      var item = default(T);

      for( int i = 0; i < weights.Length; i++ )
      {
         max = min + weights[i];
         item = items[i];
         if( rand >= min && rand <= max )
         {
            break;
         }
         min = min + weights[i];
      }

View on GitHub (pinned to 6ece18c5c2)

Solutions

  1. Ensure weights.Length == items.Length before calling.
  2. Generate weights from items with a single pass so they stay aligned.
  3. Add a debug assert: System.Diagnostics.Debug.Assert(weights.Length == items.Length).

Example fix

// before
var pick = f.Random.WeightedRandom(items, weights);
// after
if (weights.Length != items.Length) throw new InvalidOperationException("length mismatch");
var pick = f.Random.WeightedRandom(items, weights);
Defensive patterns

Strategy: validation

Validate before calling

static T SafeWeighted<T>(Bogus.Randomizer r, T[] items, float[] weights) {
    if (weights.Length != items.Length) throw new InvalidOperationException("items/weights length mismatch");
    return r.WeightedRandom(items, weights);
}

Type guard

bool SameLength<T>(T[] items, float[] weights) => items.Length == weights.Length;

Try / catch

try { return r.WeightedRandom(items, weights); }
catch (ArgumentOutOfRangeException ex) when (ex.Message.Contains("Length must be the same")) {
    // resize/normalize weights to match items, then retry
}

Prevention

When it happens

Trigger: Calling f.Random.WeightedRandom(items, weights) where the two arrays have different element counts.

Common situations: Building items and weights from separate sources and missing a sync; editing one list and forgetting the other.

Related errors


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