Range

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I am trying to create a method that checks if a value is in a range:

public static bool Range(double value, double? minimum, double?
maximum) {
....

Is it possible to make this function to check ranges of any type of
numerical values?

For example, I could want to test the range of int values ...

Thanks,
Miguel
 
shapper said:
Hello,

I am trying to create a method that checks if a value is in a range:

public static bool Range(double value, double? minimum, double?
maximum) {
...

Is it possible to make this function to check ranges of any type of
numerical values?

For example, I could want to test the range of int values ...

Thanks,
Miguel

You can make the method compare any value type that is comparable:

public static bool Range<T>(T value, T? min, T? max) where T : struct,
IComparable<T> {
if (min.HasValue && value.CompareTo(min.Value) < 0) return false;
if (max.HasValue && value.CompareTo(max.Value) > 0) return false;
return true;
}
 
You can make the method compare any value type that is comparable:

public static bool Range<T>(T value, T? min, T? max) where T : struct,
IComparable<T> {
        if (min.HasValue && value.CompareTo(min.Value) < 0) return false;
        if (max.HasValue && value.CompareTo(max.Value) > 0) return false;
        return true;

}

Thank you. That is really useful ...
 
Back
Top