theaob
theaob

Reputation: 179

How to determine if a generic number parameter is unsigned?

I have a generic method to generate random numbers within a minimum and a maximum. I also have a similar function for generating out-of-bounds values with the same limits.

But the thing is, I have different types of variables that I need to fill out. Some variables are unsigned and the minimum-maximum range is the same as the unsigned type that they are.

When I try to create out-of-bounds value for these variables, I exceed the limit of the variable (ushort to be exact).

This is my generic method:

    private static U GenerateOutOfBounds<U>(U minimum, U maximum) where U : IComparable, IFormattable, IConvertible
    {
        bool b       = g.NextBoolean();
        long signCheckForMinimum = Convert.ToInt64(minimum);
        double maxpp = g.NextDouble(Convert.ToDouble(maximum), Convert.ToDouble(maximum) + g.Next());
        double minpp = g.NextDouble(Convert.ToDouble(maximum), Convert.ToDouble(maximum) + g.Next());
        if (signCheckForMinimum >= 0)
        {
            b = true;
        }

        if (b)
        {
            return (U)Convert.ChangeType(maxpp, Type.GetTypeCode(typeof(U)));
        }
        else
        {
            return (U)Convert.ChangeType(minpp, Type.GetTypeCode(typeof(U)));
        }
    }

I tried to determine if the number is unsigned with casting it to long but I can now see that approach is very false.

So how can I determine if the variable I got is unsigned or is there any way to check if the type is unsigned without comparing with all unsigned types?

Upvotes: 6

Views: 2226

Answers (2)

maciej-ka
maciej-ka

Reputation: 575

bool signed = Convert.ToBoolean(typeof(U).GetField("MinValue").GetValue(null));

Signed types have nonzero MinValue constant, which will convert into true during boolean cast.

Upvotes: 13

EdFred
EdFred

Reputation: 711

I would answer this by comparing param == abs(param) so that you can determine if it's negative and handle it respectively. You could try to upconvert to a double (or the largest possible signed number type so that you don't lose any precision).

Upvotes: 0

Related Questions