In this exercise you will try the interfaces
These interfaces are most important in sorting, etc.
Create a new Solution in Visual Studio. Name the Solution "ComparingObjects".
Create a new class Teacher with properties:
Methods:
The Teacher class must implement the interface IComparable<Teacher>. The CompareTo(Teacher other) should use the Id property to compare Teacher objects.
Hint: return this.Id - other.Id
This is known as the "minus trick". It works because CompareTo must return an integer, but only the sign of the integer really matters:
Unit test this class, specially the CompareTo(...) methods (from the IComparable<Teacher> interface).
In the Main method create a List<Teacher> and add at least 3 teacher objects to the list.
Write the list to the screen.
Sort the list by calling the method List.Sort().
Write the list to the screen, and see that it is now sorted by Id: Sort used Teacher.CompareTo(...) while sorting.
The next step is to sort the list of Teachers by Name.
Of course you can change the Teacher.CompareTo(...) method to compare by Name, but that is not what I want: I want to keep CompareTo(...) as is is and then make another method. However, you cannot make another CompareTo(Teacher t) in the class Teacher {you cannot have two methods with the same signature in a single class}.
Create a new class TeacherNameComparer.
IComparer<Teacher> has a single method
public int Compare(Teacher x, Teacher y)
Implement this method without if statements.
Hint: return x.Name.CompareTo(y.Name)
The class TeacherNameComparer should NOT be public.
Instead you should make a static field in the Teacher class
public static readonly IComparer<Teacher> NameComparer = new TeacherNameComparer();
Benefits, over a public class
Unit test the TeacherNameComparer (using the static field NameComparer)
In the Main method sort the list of Teacher objecs by name
list.Sort(Teacher.NameComparer);
Write the list to the screen, and see that the list is now sorted by name.
I would be nice if we could move the TeacherNameComparer into the Teacher class ...
We only need to add two features to the Teacher class
Just two lines:
private static readonly IComparer<Teacher> NameComp = new TeacherNameComparer();
public static IComparer<Teacher> NameComparer { get { return NameComp; } }
Refactor Main (the latest call to Sort) to use the property NameComparer.
Now you have to make yet another class TeacherNameSalaryComparer. It must compare by
If two teachers have the same Name, the Salary should be used for a second-level compare.
Now you are allowed to use an if statement (but only ONE) in the CompareTo(...) method.
Sometimes we want to do a reverse sort, for example sort the Teacher by Id starting with the highest Id.
Of course we could define yet another Comparator class, but it would be nicer if we could program a generice ReverseComparator class ...
As TeacherNameComparer, but now you want to compare teachers by Salary.