Implementing Interfaces: Comparing Objects Using a Separate Class

Learn how to compare objects and sort instances of a type without direct access to its source code.

Comparing objects using a separate class

Sometimes, we won’t have access to the source code for a type, and it might not implement the IComparable interface. Luckily, there is another way to sort instances of a type. We can create a separate type that implements a slightly different interface, named IComparer:

Step 1: In the PacktLibrary project, add a new class file named PersonComparer.cs containing a class implementing the IComparer interface that will compare two people, that is, two Person instances. Implement it by comparing the length of their Name field, or if the names are the same length, then compare the names alphabetically, as shown in the following code:

Get hands-on with 1400+ tech skills courses.