1

I'm writing a function to take two bounds (lower, higher), a preset middle, and a percentage roll, to simulate picking a random number if it is chosen. Rather than write two or three functions that do exactly the same thing bar a cast on return, I decided to take advantage of the generic math feature in .NET 7.0.

However, you can't do a multiplication operator between T and double.

I've considered manual multiplication operators, but I'd run right into the same problem. I can't convert the double to T, because there's an need for it to handle integers. Casting won't work for the same obvious reason. I'd rather not convert this back to non-generics, since I'd like to support other types than Int32 and Double.

Here is the function code:

    public static T RollWithVariance<T>(T lower, T middle, T higher, double percentageRoll, bool useVariance) where T : INumber<T>
    {
        if (lower > higher)
            throw new ArgumentException($"The parameter for lower: {lower} must be lower than higher: {higher}", nameof(lower));
        if (lower > middle)
            throw new ArgumentException($"The parameter for lower: {lower} must be lower than middle: {middle}", nameof(lower));
        if (middle > higher)
            throw new ArgumentException($"The parameter for middle: {middle} must be lower than higher: {higher}", nameof(middle));

        if (lower == higher && lower != middle)
            throw new ArgumentException("The parameters for the lower and upper bound are the same, but the middle is another value. Please make sure either all three are the same, or none are the same. (Alternatively, consider not using this function for this invoke.)", nameof(lower));

        if (lower == middle && middle == higher) //if all three params are the same, return the same.
            return middle;

        if (useVariance)
            return lower + ((higher - lower) * percentageRoll);
        else
            return middle;
    }

EDIT: I've seen the suggested solution, and the issue is that, again, if T is an integer, converting the percentageRoll, which should be between [0,1] to that T, will not produce anything useful, an in fact, would produce buggy code.

Sakorona
  • 11
  • 3

0 Answers0