I really hate working with IComparer - to this day, after years of working with .Net, I still get regularly confused by those 1s and -1s.
Can I somehow replace the Compare result values with some self-explanatory names without having to cast the output integers to something else after every Compare call?
I tried to define an enum like this:
public enum ComparerResult
{
ALessThanB = -1,
Equal = 0,
AGreaterThanB = 1
}
if(comparer.Compare(a, b) == ComparerResult.ALessThanB)
But that of course won't compile without a cast.
This of course also applies to IComparable.CompareTo.
Thanks for your ideas
I prefer this to express less-than:
if (comparer.Compare(a, b) < 0)
This is a nice mnemonic because you use the same operator for comparison with zero as you would between the two operands.
As Reddog reminded me in the comments, the specification for the interfaces does not require -1 and 1 specifically; it only requires negative and positive results. As such, the logic you're currently using is not guaranteed to work in all cases.