I am sure that there is a simple explanation but cannot work out the following:
const short amount = 30000;
bool isGreater =
ComparableExtensions.IsGreaterThan(amount, 29000); //returns true
bool isGreaterThan2 =
amount.IsGreaterThan<short>(29000);//returns false
public static class ComparableExtensions
{
public static bool IsGreaterThan<T>(this T leftValue, T rightValue)
where T : struct, IComparable<T>
{
var result = leftValue.CompareTo(rightValue) == 1;
return result;
}
}
Is it because i put a “Struct” contraint?
any explanation or suggestions?
thanks
No, your mistake using
leftValue.CompareTo(rightValue) == 1.Instead, say
leftValue.CompareTo(rightValue) > 0.All you know is that
CompareToreturns< 0ifleftValueis less thanrightValue,0ifleftValueequalsrightValueand> 0ifleftValueis greater thanrightValue. You can not only check for equality with1.Additionally, the reason that you see different behavior between the two calls is because in the first case you are calling
IsGreaterThan<int>because the literal constant29000will be interpreted asInt32, but in the second case you explicitly sayshortso it will be interpreted asInt16.