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?
Signed types have nonzero
MinValueconstant, which will convert intotrueduring boolean cast.