Skip to content
David Cumps
Exam 70-536 study notes

Comparer Class

Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).

Overview

Good practice

  • When possible, use the generic version of IComparer<T> and Comparer<T>.

Examples

Compare Strings

// Returns 0 when equal, less than 0 when a < b and greater than 0 when a > b
Console.WriteLine("Is a equal to b? {0}", Comparer.DefaultInvariant.Compare("a", "b"));

Reverse Sort

public class Program
{
    static void Main(string[] args)
    {
        ArrayList a = new ArrayList();
        a.AddRange(new string[] { "Hello", "World", "Aloha" });
        a.Sort();
        foreach (object s in a) { Console.WriteLine(s); }
        a.Sort(new ReverseSort());
        foreach (object s in a) { Console.WriteLine(s); }
    }
}
 
public class ReverseSort : IComparer
{
    public int Compare(object x, object y)
    {
        return y.ToString().CompareTo(x.ToString());
    }
}

You May Also Like