Question

I've got a method like this:

public static bool IsPercentage<T>(T value) where T : IComparable
{
    return value.CompareTo(0) >= 0 && value.CompareTo(1) <= 0;
}

I would like to use this to validate if any number falls in the range 0 <= N <= 1. However this only works with integers since CompareTo only operates on equal types. Is there a different way to do this?

Was it helpful?

Solution

well you could use Convert.ToDecimal, then you don't need to be generic:

public static bool IsPercentage(Object value)
{
    decimal val = 0;
    try
    {
        val = Convert.ToDecimal(value);
    }
    catch
    {
        return false;
    }
    return val >= 0m && val <= 1m;
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top