-4

I understand the "CompareTo compares the instance and the value(represented in my code by amountA - instance and amountB-value) and it could return 1, -1 or 0 depending on what we have for the instance and value.

Could anyone explain me why it returns 1,-1 or 0? Although I was able to use it, I'd like to understand this method a bit better.

Thank you!

See bellow my C# code//

        if (Math.Round(amountA, 2).CompareTo(Math.Round(amountB, 2)) == 0)   
        {
            return ("Plan " + planA.Name + " costs " + amountA) + " " + ("Plan " + planB.Name + " costs " + amountB) + " " + message3;
        }
        else if (amountA.CompareTo(amountB) > 0)
        {
            return ("Plan " + planA.Name + " costs " + amountA) + " " + ("Plan " + planB.Name + " costs " + amountB) + " " + message1;
        }
        else if (amountA.CompareTo(amountB) < 0)
        {
            return ("Plan " + planA.Name + " costs " + amountA) + " " + ("Plan " + planB.Name + " costs " + amountB) + " " + message2;
        }

        return "";
    }
jsbrcad
  • 33
  • 1
  • 7

1 Answers1

1

First off, The CompareTo(obj) method returns a positive number (In case obj is smaller) or a negative number (in case obj is larger), not necessarily +1 and -1 in the respective cases.

Now, Let's say you have created a class Foo with Compare(Foo item) method defined (i.e it inherits IComparable<Foo>) and create two objects bar1 and bar2 of it.

For any objects that support operators > or <, you can compare them using

if(bar1 > bar2) { ... }   // Case 1
if(bar1 < bar2) { ... }   // Case 2

if(bar1 >= bar2) { ... }  // Case 3
if(bar1 <= bar2) { ... }  // Case 4

However that is not usually the case. So you use the Compare() method as follows in all the cases:

if(bar1.Compare(bar2) > 0) { ... }   //Case 1
if(bar1.Compare(bar2) < 0) { ... }   //Case 2

if(bar1.Compare(bar2) >= 0) { ... }  //Case 3
if(bar1.Compare(bar2) <= 0) { ... }  //Case 4

Noting the similarities in both cases, I hope it is clear now why this convention for ICompare() is followed.

AzuxirenLeadGuy
  • 2,470
  • 1
  • 16
  • 27