Hi,
Sorting and comparing is often a little confusing to begin with, but if you think about what the Sort method is actually doing it can help.
When you call racers.Sort, the list will think, OK I've got all these Racer objects, and I've got to somehow put them in the right order. Luckily I got passed this RacerComparer object to help me...
Because RacerComparer implements IComparer<Racer>, the list knows that if it passes any TWO Racer objects to RacerComparer.Compare(), it will get told which one should come first. So it goes through all the possible pairs of Racers it contains and passes them to the Compare method. Depending on what gets returned, it will add them into the appropriate place in the list.
In terms of the list<T> part, remember T get replaced with whatever Type of object we are dealing with. If we tried using a RacerComparer with a List<int>, it would be sending numbers to the Compare method, which obviously doesn't make sense. By using IComparer<Racer> the compiler knows we are using the correct sort of object.
Hopefully this hasn't confused you even more!
Phil
|