I'm wondering because the MSDN documentation says the following:
Less than zero: This instance is less than value.
Zero: This instance is equal to value.
Greater than zero: This instance is greater than value.
If you just want to compare a value being less, equal or greater, why not just use -1, 0 and 1?
There are two things to consider here.
The actual implementation might currently always return -1, 0, or 1, never anything else. Note that I have not verified this.
However, the documentation specifies that it is legal to use negative values, and positive values, not just -1 and +1.
This means that for you to write robust code using .CompareTo
, you need to handle negative and positive values, not just -1 and +1.
Note that this does not mean that you cannot return -1 and +1 from your own implementations of CompareTo
, but you need to be prepared for any other values as well.
For simplicity, in some cases, an implementation might just return the result of subtracting one value from another, and thus you will get something that isn't -1 or +1.
This question is probably way to broad but I at least know of many such implementations in use at my company, because I wrote them:
public int CompareTo(Student other)
{
return this.Grade - student.Grade;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With