Implementing a "between" Function for Range Checking in C#

Dec 05, 2025 · Programming · 11 views · 7.8

Keywords: c# | extension method | range checking | between | C# programming

Abstract: This paper addresses the need to check if a value lies within a specified range in C#, noting the absence of a built-in "between" function in the standard library. By analyzing the best answer, it introduces how to create an extension method to achieve this functionality, supporting custom boundary conditions such as inclusive or exclusive endpoints. The article provides a detailed explanation of the code implementation, including the use of extension methods and conditional logic, and references other answers to discuss generic versions and different boundary combinations. Aimed at C# developers, it offers practical examples and a summary, emphasizing the importance of custom extension methods in improving code readability and reusability.

Problem Background

In C# programming, developers often need to check if a value is between two other values, for instance, to validate input within a valid range or for conditional logic. However, the C# standard library lacks a built-in "between" function, which can lead to manual code implementation, potentially increasing complexity and error risk.

Core Implementation

Based on the best answer, we can create an extension method to check if an integer is within a specified range. This method allows control over whether boundaries are inclusive via a parameter, offering flexibility. The key code implementation uses extension method syntax and conditional operators.

public static bool Between(this int num, int lower, int upper, bool inclusive = false)
{
    return inclusive
        ? lower <= num && num <= upper
        : lower < num && num < upper;
}

This code defines an extension method named Between for the int type. It takes three parameters: num (the value to check), lower (the lower bound), upper (the upper bound), and an optional inclusive boolean parameter defaulting to false, indicating whether boundaries are included. When inclusive is true, a closed interval is used (lower <= num && num <= upper); otherwise, an open interval is used (lower < num && num < upper). This is concisely achieved with the conditional operator.

Code Analysis

Extension methods enable adding new methods to existing types (like int) without modifying the original type. Here, the Between method uses the this keyword to treat int as the first parameter, making calls more intuitive. Comparison operations use standard relational operators for efficient execution. The conditional operator (? :) provides clear logical branching, enhancing code readability.

Extended Versions

Referencing other answers, this method can be extended to support generic types and different boundary conditions. For example, using the IComparable<T> interface to implement generic range checking for various data types (e.g., floats, strings). Below is an example of a generic extension method based on the first answer.

public static bool IsBetween<T>(this T item, T start, T end) where T : IComparable<T>
{
    return Comparer<T>.Default.Compare(item, start) >= 0
        && Comparer<T>.Default.Compare(item, end) <= 0;
}

This method employs Comparer<T>.Default for comparisons, ensuring type safety. The third answer provides a more comprehensive class supporting four boundary combinations (e.g., IsBetweenII, IsBetweenEI), with suffixes indicating inclusive (I) or exclusive (E) boundaries. This allows precise control over range checking but may add complexity. Developers can choose implementations based on specific needs.

Application Examples

In practice, extension methods can be directly invoked on values, improving code conciseness. For example, checking if 5 is between 0 and 10 with inclusive boundaries.

bool b = 5.Between(0, 10, true); // Returns true

If the inclusive parameter is not specified, it defaults to false, checking an open interval.

bool c = 5.Between(0, 10); // Returns true, as 5>0 and 5<10

For the generic version, it can be applied to other types.

double d = 5.5;
bool e = d.IsBetween(5.0, 6.0); // Returns true

Conclusion

Although C# does not have a built-in "between" function, range checking can be easily implemented via extension methods. The best answer offers a simple and flexible integer-checking method, while other answers extend support to generics and boundary options. It is recommended that developers implement similar methods in their projects to enhance maintainability and readability. This approach not only addresses common needs but also demonstrates the power of C# extension methods.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.