Search code examples
c#genericsnumbers.net-8.0.net-generic-math

Generic PostitiveNumber struct in C#


I am trying to create a concept of positive numbers only, using the record struct and the INumber<T> interface. I expected this to work:

public record struct PositiveNumber<T>(T Value) where T : INumber<T>
{
    public T Value { get; init; } = Value >= 0 ? Value : throw new ArgumentOutOfRangeException(nameof(Value));
}

This causes a compile error on Value >= 0 saying that

Operator >= cannot be applied to operands of type 'T' and 'int'.

I thought constraining the generic to INumber<T> solves this. Is this not possible, or am I doing something wrong here?


Solution

  • You can use INumberBase<TSelf>.Zero:

    public record struct PositiveNumber<T>(T Value) where T : INumber<T>
    {
        public T Value { get; init; } = Value >= T.Zero ? Value : throw new ArgumentOutOfRangeException(nameof(Value));
    }
    

    Also might be useful: