Does c# have a function that returns a boolean for expression : if(value.inRange(-1.0,1.0)){}
?
If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.
Using range in switch case in C/C++ You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.
const inRange = (num, num1, num2) => Math. min(num1, num2) <= num && Math. max(num1, num2) >= num; Could be like this if you want to make inRange inclusive and not depend on order of range numbers (num1, num2).
I suggest you use a extension method.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
You can create this extension method in a generic way (thx to digEmAll and CodeInChaos, who suggest that). Then you can use that on every object that implements IComparable
.
public static class IComparableExtension
{
public static bool InRange<T>(this T value, T from, T to) where T : IComparable<T>
{
return value.CompareTo(from) >= 1 && value.CompareTo(to) <= -1;
}
}
then you do this
double t = 0.5;
bool isInRange = t.InRange(-1.0, 1.0);
After an extensive discussion with @CodeInChaos who said
I'd probably go with IsInOpenInterval as suggested in an earlier comment. But I'm not sure if programmers without a maths background will understand that terminology.
You can name the function IsInOpenInterval
too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With