Question

I have to parse the content of many TextBox that contain various numeric data types (int, double, ...). To be valid, the text does not only have to be parsable as int, or dobule or whatever, it also has to be in a certain range.

I have this function:

    private static bool validateDoubleInRange(TextBox txtBox,
        double rangeMin, double rangeMax,
        string errorMessage, ErrorProvider ep, out double? result)
    {
        double tmpResult;
        if (double.TryParse(txtBox.Text, out tmpResult))
        {
            // Ok it's a double but is it valid?
            if (tmpResult > rangeMin && tmpResult < rangeMax)
            {
                // Yes it is
                result = tmpResult;
                ep.SetError(txtBox, string.Empty);
                return true;
            }
            else
            {
                // No
                result = null;
                ep.SetError(txtBox, errorMessage);
                return false;
            }
        }
        else
        {
            // Not even a double
            result = null;
            ep.SetError(txtBox, errorMessage);
            return false;
        }
    }

This works for fields that i know should contain a double. To parse a field that should contain an int i would need to write a function that is almost identical except for the double.TryParse(string, out double) that would become int.TryParse(string, out int) and the signature of the function that would change from out double? to out int?

I've created a delegate to be used instead of the type specific type.TryParse(...):

private delegate bool GenericTryParse(TextBox txtBox, out ??? result);

the previous function would contain en extra parameter that will be of type GenericTryParse

And the call (int version) would become:

validateGenericNumberInRange(txtBox, 0, 100, errorMessage, ep,
 (TextBox tb, out int r) => { return int.TryParse(tb.Text, out r)?true:false; },
 out result);

The problem is, i'm still bound to the out parameter type, i can't (or don't know how to) declare GenericTryParse without specifying the out result type.

Is there a way around this problem, how would you do that?

Was it helpful?

Solution

You're looking for generics:

private delegate bool GenericTryParse<T>(TextBox txtBox, out T result);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top