Comparer Class
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
Overview
- Used as the default comparer when sorting with ArrayList for example.
- 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, -1 when a < b and 1 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 (var s in a) { Console.WriteLine(s); }
a.Sort(new ReverseSort());
foreach (var 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
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



