Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If value in range(x,y) function c#

Tags:

c#

range

Does c# have a function that returns a boolean for expression : if(value.inRange(-1.0,1.0)){}?

like image 833
SevenDays Avatar asked Jan 08 '12 09:01

SevenDays


People also ask

How do you check if a number is within a range?

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.

Is there range function in C?

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.

How do you check if a value is within a range in Javascript?

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).


1 Answers

Description

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.

Solution

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);

Update for perfectionists

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.

More Information

  • MSDN - Extension Methods (C# Programming Guide)
  • MSDN - IComparable Interface
like image 118
dknaack Avatar answered Oct 02 '22 08:10

dknaack