I have a function that verifies if a number falls between two other numbers a and b. For doubles this function looks like this:
public static bool IsBetween(this double num, double minValue, double maxValue)
{
return (num >= minValue && num <= maxValue)
|| (num >= maxValue && num <= minValue);
}
The problem here, however is that I need to be able to check if integer or decimal falls within this range. So I would have to specify an overload with signature:
public static bool IsBetween(this int num, double minValue, double maxValue)
Question: is there a way to make this universal by adding where T is inherited from IComparable. Here is what I am looking for:
public static bool IsBetween <T : IComparable> (this T num, K minValue, K maxValue)
{
return (num >= (T)minValue && num <= (T)maxValue)
|| (num >= (T)maxValue && num <= (T)minValue);
}
I could probably try to cast everything in double but I it would be an overkill if all values are integers or decimals.
You write this as:
That being said, you might want to write this using IConvertible instead of
IComparible, given that you’re casting. This would let you do cleaner conversions to a common type.