I wrote a short article “Multilevel Sorting with IComparable and IComparer” in the current issue of Visual Studio Magazine. This is one of those topics where there is plenty of technical documentation available but the documentation doesn’t adequately (in my opinion) explain the differences between IComparable and IComparer. To summarize the two main rules of thumb in my article:
If you have a class (such as an Employee), and you will need an array or List of objects of the class, and you will be sorting the collection, then
1. If there will only be one sort order (for example by last name, ascending (alphabetical) order), then derive the class from IComparable, and code method CompareTo in the class. Sorting will be done automatically using the CompareTo method.
2. If you want several sort orders (say by last name ascending and also by pay rate descending), then do not derive the class from IComparable, but do insert a nested subclass that inherits from IComparer and inside that subclass code a Compare method for each sort. When sorting you must specify which Compare to use.
This has always seemed a little confusing to me and I’m not sure why the patterns are different. Anyway, my article is available at: