Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
theaob Avatar asked Nov 28 '12 14:11

theaob


1 Answers

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

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

like image 168
lokson Avatar answered Nov 15 '22 00:11

lokson