Humanizr/Humanizer · error · ArgumentException

Object is not a ByteRate

Error message

Object is not a ByteRate

What it means

Thrown by the non-generic ByteRate.CompareTo(object?) when the argument is not null and not a ByteRate instance. The method's pattern match handles null (returns 1) and ByteRate (delegates to the typed CompareTo); any other runtime type hits the default arm and throws ArgumentException with the message 'Object is not a ByteRate'. This implements the IComparable contract which requires type mismatch to throw ArgumentException.

Source

Thrown at src/Humanizer/Bytes/ByteRate.cs:170

    /// <inheritdoc />
    /// <remarks>
    /// Equality requires the other instance to have the same runtime type.
    /// </remarks>
    public override bool Equals(object? obj) =>
        obj?.GetType() == GetType() && Equals((ByteRate)obj);

    /// <inheritdoc />
    public override int GetHashCode() =>
        BytesPerSecond.GetHashCode();

    /// <inheritdoc />
    public int CompareTo(object? obj) =>
        obj switch
        {
            null => 1,
            ByteRate other => CompareTo(other),
            _ => throw new ArgumentException("Object is not a ByteRate", nameof(obj)),
        };

    double BytesPerSecond => Size.Bytes / Interval.TotalSeconds;
}

View on GitHub (pinned to ffc2b77c0f)

Solutions

  1. Ensure the argument to CompareTo is a ByteRate instance or null before calling the non-generic overload.
  2. Prefer the typed ByteRate.CompareTo(ByteRate) overload when both operands are known to be ByteRate.
  3. If using a non-generic collection, switch to a generic List<ByteRate> to get type safety at compile time.

Example fix

// before — non-generic CompareTo with wrong type
var cmp = byteRate.CompareTo(someByteSize); // ByteSize, not ByteRate

// after — compare two ByteRate instances
var cmp = byteRate.CompareTo(otherByteRate);
Defensive patterns

Strategy: type-guard

Type guard

static bool IsByteRate(object? obj) => obj is ByteRate;

Prevention

When it happens

Trigger: Calling byteRate.CompareTo(obj) where obj is an instance of a different type — e.g. a boxed int, a string, a ByteSize, or any other object. This can happen when ByteRate is stored in a non-generic collection or sorted via IComparable without a typed comparer.

Common situations: A developer places ByteRate instances in an ArrayList or sorts them through a non-generic API that calls CompareTo with boxed objects of mixed types. Or a comparison function receives values from an untyped source.

Related errors


AI-assisted analysis of Humanizr/Humanizer@ffc2b77c0f (2026-08-13). Data as JSON: /api/errors/4fca0f65271ecc63. Report an issue: GitHub.