Implementing IComparable

Like all collections, the
List implements the Sort( )
method, which allows you to sort any objects that implement
IComparable. In the next example,
you'll modify the Employee object
to implement IComparable:

public class Employee : IComparable<Employee>

To implement the IComparable<Employee>
interface, the Employee object must provide a
CompareTo() method:

The CompareTo( ) method takes an
Employee as a parameter. We know this is an
Employee because this is a type-safe collection.
The current Employee object must compare itself to
the Employee passed in as a parameter and return
-1 if it is smaller than the parameter,
1 if it is greater than the parameter, and
0 if it is equal to the parameter. It is up to
Employee to determine what
smallerthan,
greaterthan, and
equalto mean. In this example,
you delegate the comparison to the empId member.
The empId member is an int and
uses the default CompareTo( ) method for integer
types, which will do an integer comparison of the two values.

TIP:
The System.Int32 class implements
IComparable<Int32>, so you may delegate the
comparison responsibility to integers.

You are now ready to sort
the array list of employees, empList. To see if
the sort is working, you'll need to add integers and
Employee instances to their respective arrays with
random values. To create the random values, you'll
instantiate an object of class Random; to generate
the random values, you'll call the
Next( ) method on the Random
object, which returns a pseudorandom number. The
Next( ) method is overloaded; one version allows
you to pass in an integer that represents the largest random number
you want. In this case, you'll pass in the value
10 to generate a random number between
0 and 10:

Random r = new Random();
r.Next(10);

Example 9-14 creates an integer array and an
Employee array, populates them both with random
numbers, and prints their values. It then sorts both arrays and
prints the new values.