Overview
- Used as the default comparer when sorting, for example with an ArrayList.
- Implements the IComparer interface.
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

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




