How can I do this elegantly with C# and .NET 3.5/4?
For example, a number can be between 1 and 100.
I know a simple if would suffice; but the keyword to this
Cause all the other answer are not invented by me, here just my implementation:
public enum Range
{
///
/// A range that contains all values greater than start and less than end.
///
Open,
///
/// A range that contains all values greater than or equal to start and less than or equal to end.
///
Closed,
///
/// A range that contains all values greater than or equal to start and less than end.
///
OpenClosed,
///
/// A range that contains all values greater than start and less than or equal to end.
///
ClosedOpen
}
public static class RangeExtensions
{
///
/// Checks if a value is within a range that contains all values greater than start and less than or equal to end.
///
/// The value that should be checked.
/// The first value of the range to be checked.
/// The last value of the range to be checked.
/// True if the value is greater than start and less than or equal to end, otherwise false .
public static bool IsWithin(this T value, T start, T end) where T : IComparable
{
return IsWithin(value, start, end, Range.ClosedOpen);
}
///
/// Checks if a value is within the given range.
///
/// The value that should be checked.
/// The first value of the range to be checked.
/// The last value of the range to be checked.
/// The kind of range that should be checked. Depending on the given kind of range the start end end value are either inclusive or exclusive.
/// True if the value is within the given range, otherwise false .
public static bool IsWithin(this T value, T start, T end, Range range) where T : IComparable
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (start == null)
throw new ArgumentNullException(nameof(start));
if (end == null)
throw new ArgumentNullException(nameof(end));
switch (range)
{
case Range.Open:
return value.CompareTo(start) > 0
&& value.CompareTo(end) < 0;
case Range.Closed:
return value.CompareTo(start) >= 0
&& value.CompareTo(end) <= 0;
case Range.OpenClosed:
return value.CompareTo(start) > 0
&& value.CompareTo(end) <= 0;
case Range.ClosedOpen:
return value.CompareTo(start) >= 0
&& value.CompareTo(end) < 0;
default:
throw new ArgumentException($"Unknown parameter value {range}.", nameof(range));
}
}
}
You can then use it like this:
var value = 5;
var start = 1;
var end = 10;
var result = value.IsWithin(start, end, Range.Closed);