You can use Expression Tree to do this. Consider helper, static class
static class NumericHelper<T>
{
public static T Zero { get; private set; }
public static T One { get; private set; }
static NumericHelper()
{
Zero = default(T);
One = Expression.Lambda<Func<T>>(
Expression.Convert(
Expression.Constant(1),
typeof(T)
)
).Compile()();
}
}
It generates (T)1
cast at runtime and assign result to One
property. Because static constructor is fired only once code necessary to generate properly typed 1
value will be executed only once for every T
.
public static bool IsPercentage<T>(T value) where T : IComparable
{
return value.CompareTo(NumericHelper<T>.Zero) >= 0 && value.CompareTo(NumericHelper<T>.One) <= 0;
}
Ofc, it will fail if you try to call it with type T
which don't support (T)1
conversion.