Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any known implementations of .CompareTo(object value) method actually returning a value smaller than -1 or greater than 1?

Tags:

c#

.net

clr

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?

like image 998
Steven S. Avatar asked Dec 21 '22 09:12

Steven S.


2 Answers

There are two things to consider here.

  1. What is documented
  2. What is implemented

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.

like image 139
Lasse V. Karlsen Avatar answered Dec 30 '22 09:12

Lasse V. Karlsen


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;
}
like image 28
Michael Edenfield Avatar answered Dec 30 '22 09:12

Michael Edenfield