Implementing IComparable to Allow Sorting a Custom Type

Arrays of elements that belong to a custom type cannot be sorted, unless the type implements the IComparableinterface.
To make elements of a custom type sortable, you need to implement IComparable in your type.  IComparableconsists of the single method CompareTo, which compares two objects.
Here’s an example of a Person class implementing CompareTo to sort people in LastName/FirstName order:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int CompareTo(object obj)
{
    Person other = obj as Person;
    if (other == null)
        throw new ArgumentException("Object is not a Person");
    else
    {
        // Sort by LastName, then by FirstName (ignore case)
        int compare = this.LastName.ToLower().CompareTo(other.LastName.ToLower());
        if (compare == 0)
            compare = this.FirstName.ToLower().CompareTo(other.FirstName.ToLower());
 
        return compare;
    }
Here’s an example of sorting an array of Person objects:


1
2
3
4
5
6
Person[] folks = new Person[4];
folks[0] = new Person("Bronte", "Emily");
folks[1] = new Person("Bronte", "Charlotte");
folks[2] = new Person("Tennyson", "Alfred");
folks[3] = new Person("Mailer", "Norman");
Array.Sort(folks);    // C. Bronte, E. Bronte, Mailer, Tennyson