RelaxComparer : Missing IComparer?


5.CompareTo(4); // returns 1 (greater than)
5.CompareTo(5); // returns 0 (equal)
5.CompareTo(6); // returns -1 (less than)

// A class will only compare to its same type.
5.CompareTo('c'); // Throws ArgumentException


I created the following class to use instead of the default Comparer class (which just calls the CompareTo method of each object implementing IComparable) to perform sorting (and other comparison related algorithms) with objects of different types.


/// <summary>
/// Compares two objects for equivalence, where objects of different
/// types are compared by their string representations.
/// </summary>
public class RelaxComparer : IComparer
{
public int Compare(object x, object y)
{
Type typeX = x.GetType(), typeY = y.GetType();
/* IComparable.CompareTo(object obj) The parameter, obj, must be
* the same type as the class or value type that implements this
* interface; otherwise, an ArgumentException is thrown */
if (typeX == typeY && typeof(IComparable).IsAssignableFrom(typeX))
return ((IComparable)x).CompareTo(y);
else
return x.ToString().CompareTo(y.ToString()); // use strings
}
}


So now you can add strings, chars, ints in any order and sort the items with the sort method of ArrayList:


char[] chars = new char[] { 'a', 'd', 'c', 'b' };
int[] ints = new int[] { 4, 3, 1, 2, 0 };
char[] CHARS = new char[] { 'B', 'C', 'D', 'A' };

ArrayList arrayList = new ArrayList();

foreach(char x in chars)
arrayList.Add(x);

foreach(int x in ints)
arrayList.Add(x);

foreach(char x in CHARS)
arrayList.Add(x);

arrayList.Sort(new RelaxComparer());

foreach(object o in arrayList)
Console.Write(string.Format("{0} ", o));

// output: 0 1 2 3 4 A B C D a b c d