In chapter 11, there is a Try It Out section about using Sorting with IComparable.
Below is the line that called the sorting method
Code:
Console.WriteLine("People sorted with default comparer (by age):");
list.Sort();
When I debugged it, that line goes to CompareTo method just like the book explained, but I don't understand how the CompareTo method ended up sorting the ArrayList. I just do not see how this happens even after I debug the code. Can anyone explain why the code below works to sort the ArrayList? I do not see that the code change the position of the items in the ArrayList.
Code:
public int CompareTo(object obj)
{
if (obj is Person)
{
Person otherPerson = obj as Person;
return this.Age - otherPerson.Age;
}
else
{
throw new ArgumentException("Object to compare to is not a Person object.");
}
}