2.2. Determining Whether a Character Is Within a Specified Range

Problem

You need to determine whether a character in a char data type is within a range, such as between 1 and 5 or between A and M.

Solution

Use the built-in comparison support for the char data type. The following code shows how to use the built-in comparison support:

public static bool IsInRange(char testChar, char startOfRange, char endOfRange)
{
    if (testChar >= startOfRange && testChar <= endOfRange)
    {
        // testChar is within the range
        return (true);
    }
    else
    {
        // testChar is NOT within the range 
        return (false);
    }
}

There is only one problem with that code. If the startOfRange and endOfRange characters have different cases, the result may not be what you expect. By adding the following code, which makes all characters uppercase, to the beginning of the method in Recipe 2.7, we can solve this problem:

testChar = char.ToUpper(testChar);
startOfRange = char.ToUpper(startOfRange);
endOfRange = char.ToUpper(endOfRange);

Discussion

The IsInRange method accepts three parameters. The first is the testChar character that you need to check on, to test if it falls between the last two parameters on this method. The last two parameters are the starting and ending characters, respectively, of a range of characters. The testChar parameter must be between startOfRange and endOfRange or equal to one of theses parameters for this method to return true; otherwise, false is returned.

The IsInRange method can be called in the following ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.