Thursday, March 8, 2012

Extension method - BETWEEN function

Well, on and off we need to increase the readability of the code and also reduce the typo mistake in the comparison symbols. Here is how you can achieve it:

        public static bool IsBetween(this int value,
            int i,
            int i2)
        {
            return ((value >= i)
                    && (value <= i2));
        }
Now, you may write this code for the integer data type:
        int i = 5;
        if (i.IsBetween(1, 12))
        {
           // the value is between 1 and 12
        }
        else
        {
           // the value is out of range.
        }

By using extension method, you may create IsBetween() method for each data type and also your own data classes.

No comments:

Post a Comment