Struggling to come up with a generic C # method that compares various types of numeric objects

I have an Infragistics UltraNumericEditor (version 5.3, quite old) managing the form.

If I set the .Value field to a smaller .MinValue or something larger .MaxValue, then I get a System.Exception message with the message:

The Value property cannot be set to a value outside the range defined by the MinValue and MaxValue properties.

The signatures of the corresponding fields on UltraNumericEditor are as follows:

public object MinValue { get; set; }
public object MaxValue { get; set; }    
public object Value { get; set; }

This can happen many hundreds of times through our code base, so instead of checking MinValue and MaxValue against the value that we try to set each time, I thought I would subclass the control and put a check there:

public class OurNumericEditor : Infragistics.Win.UltraWinEditors.UltraNumericEditor  
{  
    public object Value  
    {
        get
        {
            return base.Value;
        }
        set
        {
            // make sure what we're setting isn't outside the min or max
            // if it is, set value to the min or max instead

            double min = (double)base.MinValue;
            double max = (double)base.MaxValue;
            double attempted = (double)value;

            if (attempted > max)
                base.Value = max;
            else if (attempted < min)
                base.Value = min;
            else
                base.Value = value;
        }
    }
}

, , , MinValue MaxValue , InvalidCastException, .

, , , , , .

?


+1
4

, .

Convert double:

double min = Convert.ToDouble(base.MinValue);
double max = Convert.ToDouble(base.MaxValue);
double attempted = Convert.ToDouble(value);

, , , MinValue int value double.

+2
+4

Generics , Value . IConvertible, , (, double).

+1

, , , IComparable, , .

, , , , - :

public OurNumericEditor<T> : Infragistics.Win.UltraWinEditors.UltraNumericEditor  

 public T Value  
    {
        get
        {
            return (T) base.Value;
        }
        set
        {
            // make sure what we're setting isn't outside the min or max
            // if it is, set value to the min or max instead

            double min = (double)MinValue;
            double max = (double)MaxValue;
            double attempted = // explicit conversion code goes here

            if (attempted > max)
                base.Value = max;
            else if (attempted < min)
                base.Value = min;
            else
                base.Value = value;
        }
    }
}
+1

All Articles