Search code examples
c#comparecompareto

Implement CompareTo() - compare by various functions


I implemented CompareTo() like so:

 public override int CompareTo(object obj)
 {
   //quick failsafe
   MyClass other;
   if (obj is MyClass)
   {
     other = obj as MyClass;
   }
   else 
   { 
     return 1; 
   }
   //now we should have another comparable object.
   /*
    * 1: this is greater.
    * 0: equals.
    * -1: this is less.  
    */
   if (other.GetValue() < this.GetValue())
   {
     // this is bigger
     return 1;
   }
   else if (other.GetValue() > this.GetValue())
   {
     //this is smaller
     return -1;
   }
   else 
   { 
     return 0; 
   }
}

However, things get interesting when I want to chose the function GetValue(). I have a couple of them set up for that: namely Average(), Best(), CorrectedAverage(), Median(). I compare by an array of floats by the way. Thing is, I don't want to use a switch-case on an enum I defined in this class to tell what to order by. Is there a way that I decide which function to order by nice and clean?


Solution

  • Given that your class has a whole bunch of different ways of comparing it, it almost certainly shouldn't implement IComparable at all.

    Instead, create IComparer<T> instances for each different way of comparing your object. Someone who wants to comparer instances of the type can then pick the comparer that uses the comparison that's most appropriate for their situation.