Search code examples
c#comparable

Comparing numbers Get different result


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


Solution

  • No, your mistake using leftValue.CompareTo(rightValue) == 1.

    Instead, say leftValue.CompareTo(rightValue) > 0.

    All you know is that CompareTo returns < 0 if leftValue is less than rightValue, 0 if leftValue equals rightValue and > 0 if leftValue is greater than rightValue. You can not only check for equality with 1.

    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 constant 29000 will be interpreted as Int32, but in the second case you explicitly say short so it will be interpreted as Int16.