This is more of an academic exercise than anything else, so I'm basically just trying to get my head around how to use IComparable when the types are different.
So say we have have a fruit class, and derived classes "Apple" and "Orange". Say that I want to a list of fruit to have all the apples before the oranges. What is the best way of going about this?
I think you could just make Fruit implement the interface IComparable and put a bunch of conditional statements in for very subtypes, but this seems very crude to me and probably violates the open/closed principle. I'm more interested in getting it to work this way:
public abstract class Fruit : IComparable<Fruit>
{
public abstract int CompareTo(Fruit other);
}
public class Apple : Fruit, IComparable<Orange>
{
public override int CompareTo(Fruit other)
{
if(other is Orange)
{
this.CompareTo((Orange)other);
}
return 0;
}
public virtual int CompareTo(Orange other)
{
return -1;
}
}
public class Orange : Fruit, IComparable<Apple>
{
public override int CompareTo(Fruit other)
{
if (other is Apple)
{
this.CompareTo((Apple)other);
}
return 0;
}
public virtual int CompareTo(Apple other)
{
return 1;
}
}
My main goal here is to get IComparable working with cross types. I tried loading a list up with various fruit but alas it did not sort. Perhaps my understanding of the return value of CompareTo is a bit wonky. Is there any hope for this type of method and is there any scenario where it might be more useful than the obvious approach?
I think it feels kinda wonky is because there is no natural order of Apples and Oranges. In this specific instance you prefer apples over oranges, but maybe the next guy wants it the other way round. Or it's a mix in the winter? The point is that Apples and Oranges don't have one unique sorting alorithm and it feels wrong to build it into either Apples or Oranges or even Fruit.
That is where IComparer
comes in. You can put your comparison logic in there, but you can have many comparers and select another one with each sort you do. So you implement an ApplesFirstComparer
for the winter and then an OrangesWithTheMostOrangeColorOnTopDoNotCareForColorOfApplesComparer
and another one and another one. Basically one for each comparison you need, without implying that Apples and Oranges have a natural order. Because they don't.