I mentioned the usefulness of overriding Object’s virtual methods of Equals and ToString as well as implementing IFormattable for custom formatting.
One of the other useful interfaces you can implement for your custom class is IComparable. It has one method.
This interface comes into play when you start adding your custom objects into Arrays and ArrayLists. An ArrayList, for example, has a Sort method that allows you to sort the objects in the ArrayList. By default, the ArrayList uses the IComparable interface on each of the objects to do the sorting.
In the following example I have taken my person class and implemented IComparable. At the very end of the Person class you will see the CompareTo method. I first check to see if the object to be compared is of the same type (Person) and cast is accordingly. In my implementation I decided to only sort by firstname ascending and thus delegated all the effort of comparison to _firstname, which is of type String and also supports IComparable.
When you run the example, which fills a list of Person objects into an ArrayList, called people, it essentially calls people.Sort() which will re-order the objects ascending by firstname. Very boring, but a hell of a lot better than implementing a sort algorithm yourself.
So, the example is pretty dang limiting as I can’t vary the way I want this ArrayList sorted. Maybe I want to sort the objects by age sometimes or possibly lastname. This can be done in a hackish sort of way, but you have to make a couple of modifications.
In the example below, I first added an enum, called SortMethod, nested inside the Person Class that would allow me to specify how I want to sort the objects in the ArrayList. I also added a static property and variable, SortOrder and _sortOrder respectively, that holds the current sort method. As static members, these operate at the class level and are shared across all objects of type Person (there are drawbacks to doing this, but I won’t get into it.). I have also changed the CompareTo method to essentially vary the sorting based on the sort order.
When you run the example, it will first sort the people by firstname, which is the default, and then by lastname and finally age.
I am not going to speak about the performance of the QuickSort Algorithm, which is the algorithm used in these cases to sort the objects. Performance is a very subjective matter that is decided upon on an application-by-application basis.