Is there a “between” function in C#?

It isn’t clear what you mean by “one operation”, but no, there’s no operator / framework method that I know of to determine if an item is within a range.

You could of course write an extension-method yourself. For example, here’s one that assumes that the interval is closed on both end-points.

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

And then use it as:

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

Leave a Comment