Why is CompareTo short implemented in this way?

Consider the following code:

namespace ConsoleApplication1 {
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(100.CompareTo(200)); // prints -1
            Console.WriteLine(((decimal)100).CompareTo((decimal)200)); // prints -1
            Console.WriteLine(((short)100).CompareTo((short)200)); // prints -100
            Console.WriteLine(((float)100).CompareTo((float)200)); // prints -1
            Console.ReadKey();
        }
    } 
}

My question is, are there any specific reasons for the CompareTo method on Int16 to return values ​​other than -1, 0, and 1?

ILSpy shows that it is implemented in this way

public int CompareTo(short value)
{
    return (int)(this - value);
}

whereas the method is implemented on Int32 in this way

public int CompareTo(int value)
{
    if (this < value)
    {
        return -1;
    }
    if (this > value)
    {
        return 1;
    }
    return 0;
}
+5
source share
2 answers

The difference is that for shortthere is no possibility of overflowing the result. For example, short.MinValue - (short) 1it is still negative, while int.MinValue - 1- int.MaxValue.

, , short ( ), int. IComparable<T>.CompareTo -1, 0 1. , , .

+13

, , : , int .. / ( 2 ) , .

, , . , , , API. , short , ( short, , , int).

+5

All Articles