Checking if a Number is Within a Range in C#

Checking if a number falls within a specific range is a common task in programming. In this tutorial, we will explore various ways to accomplish this in C#, focusing on readability and elegance.

Introduction to Range Checks

A range check is a conditional statement that determines whether a given number is within a specified range, defined by a minimum and maximum value. The most basic way to perform a range check is using an if statement with two conditions: one for the lower bound and one for the upper bound.

Basic Range Check

The simplest form of a range check in C# can be written as follows:

int x = 30;
if (1 <= x && x <= 100)
{
    // Code to execute if x is within the range
}

This approach is straightforward and easy to understand. However, it’s worth noting that the order of conditions can affect readability. For instance, 1 <= x && x <= 100 is generally more readable than x >= 1 && x <= 100.

Using Pattern Matching (C# 9.0 and Later)

Starting with C# 9.0, you can use pattern matching to perform range checks in a more concise way:

int x = 30;
if (x is >= 1 and <= 100)
{
    // Code to execute if x is within the range
}

This syntax introduces a pattern matching expression where and is part of the pattern, allowing you to check both conditions without repeating the variable.

Mathematical Approach

Another elegant way to perform a range check involves using mathematical operations. This method reduces the number of comparisons from two to one:

int x = 30;
if ((x - 1) * (100 - x) >= 0)
{
    // Code to execute if x is within the inclusive range [1, 100]
}

For exclusive ranges, you can use a similar approach with strict inequalities:

if ((x - 1) * (100 - x) > 0)
{
    // Code to execute if x is within the exclusive range (1, 100)
}

This method is not necessarily more efficient but offers an alternative way of thinking about range checks.

Extension Methods for Range Checks

You can also create an extension method to make range checks more readable and reusable:

public static bool IsWithin(this int value, int minimum, int maximum)
{
    return value >= minimum && value <= maximum;
}

With this extension method, you can perform range checks as follows:

int val = 15;
bool foo = val.IsWithin(5, 20);

While this approach might seem like overkill for a simple range check, it can be useful in certain scenarios where readability and expressiveness are important.

Conclusion

In conclusion, checking if a number is within a range in C# can be accomplished in various ways, each with its own advantages. Whether you prefer the simplicity of an if statement, the elegance of pattern matching, or the creativity of mathematical approaches, there’s a method to suit your programming style and needs.

Leave a Reply

Your email address will not be published. Required fields are marked *