When you invoke the Sort method on a generic list (List in your case), behind the scenes, the implementation of Sort will check if the type of the list (the person
class) implements the IComparable interface, and if it does it will invoke the CompareTo member to perform comparisons between elements of the list to perform the sort. The fact that the person
class implements IComparable is interpreted as a "contract" that specifies that the person
class will have a method called CompareTo.
The implementation of Sort can use a snippet such as the following to compare to elements of the list:
T aPerson;
T anotherPerson;
int compareResult;
if(aPerson is IComparable)
{
compareResult = (aPerson as IComparable).CompareTo(anotherPerson);
}
The CompareTo method always compares the object it is invoked on to the parameter and the meaning of the return value is always the same:
* if the two objects are "equal", it returns 0
* if the object you are comparing to is "less than" - in a sorted list it goes before - the object you are invoking CompareTo on, it returns -1
* if the object you are comparing to is "greater than" - in a sorted list it goes after - the object you are invoking CompareTo on, it returns -1
Internally, the Sort method may employ a number of algorithms to actually perform the sort but they all revolve around comparisons. For example, the following would be a naive implementation of bubble sort which is very simple to follow and illustrates what happens behind the scenes very well:
procedure bubbleSort( A : list of sortable items ) defined as:
do
swapped := false
for each i in 0 to length(A) - 2 inclusive do:
if A[i].CompareTo(A[i+1]) > 0 then
swap( A[i], A[i+1] )
swapped := true
end if
end for
while swapped
end procedure