IComparable <T> .CompareTo () returns values?

Just a curious question about the method IComparable<T>.CompareTo()

; I know the method should return positive, negative, or null based on comparison, but does it really matter what I return in the first two cases? In other words, does it matter if I return +1 or +1000?

+3


source to share


2 answers


does it matter if i return +1 or +1000?

Do not do it. But caution says it's best to be safe both ways:



  • always returns -1, 0, +1
  • always consume with < 0

    ,> 0

+2


source


The answer is:

IComparable<T>.CompareTo()

returns the result of the subtraction for the types sbyte, short, ushort, char

and returns -1, 0 or 1 for both types int

, long

, string

etc.

var result = ((byte)10).CompareTo((byte)2); // 8
var result = ((short)1).CompareTo((byte)11); // -10
var result = ((int)10).CompareTo((int)11); // 1 ??

      

Reason for this:

First of all, consider the method signature:

int CompareTo (T other)

As you can see, the return type Int32

.

It is clear that the developers want to return the difference in values. But the return type of the subtraction Int32

can be less Int32.MinValue

or more Int32.MaxValue

. For example, let's say that:

// Return type is less than minimum int value  (-4294967296)
(Int32.MinValue).CompareTo(Int32.MaxValue) 

 // Return type is greater than maximum int value (4294967296)
(Int32.MaxValue).CompareTo(Int32.MinValue)

      

So, they decided to return the result of the subtraction for types with a "small" range of values ​​than the return type of the method that is in this case Int32

.



In the latter case, you can see the implementation of this method in all types from here :

Here's the implementationInt16

:

   public int CompareTo(Int16 value) {
            return m_value - value;
        }

      

Here's the implementationInt32

:

public int CompareTo(int value) {
            // Need to use compare because subtraction will wrap
            // to positive for very large neg numbers, etc.
            if (m_value < value) return -1;
            if (m_value > value) return 1;
            return 0;
        }

      

At the end:

But of course in the future they may change the implementation of this code, and the recommended way is to compare the result with 1, 0 or -1 always, as described in msdn.

Less than zero (This instance precedes the other in the sort order.)
Zero (This instance occurs at the same position in the sort order as the others.)
Greater than zero (This instance follows the other in the sort order.)

+3


source







All Articles