I am trying to build a method that will take a variety of numeric types and preprocess them for a second method. I am not sure if I should be simply overloading or using a generic method. I tried to use a generic method but the method does not seem to recognize the parameter type. The code is below. Can someone please explain to me whether it is better to overload or use a generic method in this case? Also, if I wanted to use a generic method to do this, how could I make it work? Thank you very much.
public static class math
{
public static int nextpow2<T>(T a)
{
double w;
if ( a.GetType() is sbyte ||
a.GetType() is byte ||
a.GetType() is short ||
a.GetType() is ushort ||
a.GetType() is int ||
a.GetType() is uint ||
a.GetType() is long ||
a.GetType() is ulong ||
a.GetType() is float ||
a.GetType() is double ||
a.GetType() is decimal
) w = (double)Convert.ChangeType(a, typeof(double));
else
throw new System.ArgumentException("Internal error in nextpow2: argument a is not a number!");
return _nextpow2(w);
}
private static int _nextpow2(double a)
{
double index = Math.Abs(a);
int p = (index > 1) ? (int)Math.Ceiling( Math.Log( index, 2.0) ) : 0;
return p;
}
I am calling the method as follows:
int indx = 0;
int p = math.nextpow2(indx);
The code fails to compile. I get the following error:
Internal error in nextpow2: argument a is not a number!
Can someone please explain what I am doing wrong? Thank you.