IComparable Vs IComparer Interface In C#

Introduction

 
Before we begin to understand these 2 interfaces, let's first understand the concept of sorting.
 
Say we have a list of integers & we want to sort them in ascending order. To achieve this we can use the direct sort method.
  1. List<int> listOfIntegaers = new List<int>() { 55, 12, 5, 78, 9, 65, 35, 5, 80, 8, 14 };  
  2. listOfIntegaers.Sort();  
  3. foreach (var item in listOfIntegaers)  
  4. {   
  5.     System.Console.WriteLine(item + " ");  

Output
 
 
This list is sorted because sort method knows it has to sort on an integer number, which is a primitive datatype in C#.
 

IComparable

 
What if I want to sort user-defined type, say user-defined class? Let's try that.
 
First, create a user-defined class SmartPhone.
 
Note: I am overriding ToString() method of the object class to print output in as per my method.
  1. public class SmartPhone : IComparable  
  2. {  
  3.     public string Name { getset; }  
  4.     public double Price { getset; }  
  5.     public string OS { getset; }  
  6.     public bool  IsFlagship { getset; }  
  7.   
  8.     public override string ToString()  
  9.     {  
  10.         return "Name: " + Name + "||"  
  11.                 + " Price: " + Price + "||"  
  12.                 + " OS: " + OS + "||"  
  13.                 + " Is flagship Phone: " + IsFlagship;  
  14.     }  

Perfect, the next step is to create a List of this object and try to use a sort function.
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.   
  6.             List<SmartPhone> smartPhones = new List<SmartPhone>()  
  7.             {  
  8.                 new SmartPhone()  
  9.                 {  
  10.                     Name = "One Plus 8",  
  11.                     IsFlagship = true,  
  12.                     OS = "Android 10",  
  13.                     Price = 55000  
  14.                 },  
  15.                 new SmartPhone()  
  16.                 {  
  17.                     Name = "IPhone 11",  
  18.                     IsFlagship = true,  
  19.                     OS = "IOS 11",  
  20.                     Price = 75000  
  21.                 },  
  22.                 new SmartPhone()  
  23.                 {  
  24.                     Name = "Samsung Note 10",  
  25.                     IsFlagship = true,  
  26.                     OS = "Android 10",  
  27.                     Price = 110000  
  28.                 },  
  29.                 new SmartPhone()  
  30.                 {  
  31.                     Name = "Samsung S20 Ultra",  
  32.                     IsFlagship = true,  
  33.                     OS = "Android 10",  
  34.                     Price = 130000  
  35.                 },  
  36.                 new SmartPhone()  
  37.                 {  
  38.                     Name = "IPhone 11 Pro",  
  39.                     IsFlagship = true,  
  40.                     OS = "IOS 11",  
  41.                     Price = 130000  
  42.                 }  
  43.             };  
  44.             smartPhones.Sort();  
  45.             foreach (var item in smartPhones)  
  46.             {  
  47.                 System.Console.WriteLine(item.ToString());  
  48.             }  
  49.         }  
  50.     } 
Now run the program.
 
 
Oops, we encountered an error. It says the user-defined class SmartPhone has to implement interface IComparable.
 
Ok, let's do that.
  1. public class SmartPhone : IComparable    
  2.   {    
  3.       public string Name { get; set; }    
  4.       public double Price { get; set; }    
  5.       public string OS { get; set; }    
  6.       public bool  IsFlagship { get; set; }    
  7.     
  8.       public int CompareTo(object obj)    
  9.       {    
  10.           if (obj == nullreturn 1;    
  11.           SmartPhone nextSmartPhone = obj as SmartPhone;    
  12.           if(nextSmartPhone != null)    
  13.           {    
  14.               return this.Price.CompareTo(nextSmartPhone.Price);    
  15.           }    
  16.           else    
  17.           {    
  18.               throw new ArgumentException("Object doesn't have a proper price");    
  19.           }    
  20.       }    
  21.     
  22.       public override string ToString()    
  23.       {    
  24.           return "Name: " + Name + "||"    
  25.                   + " Price: " + Price + "||"    
  26.                   + " OS: " + OS + "||"    
  27.                   + " Is flagship Phone: " + IsFlagship;    
  28.       }    
  29.   }     
We have to override ToCompare method. It takes one argument, the object type. So it compares the current object with the object next inline; e.g., to sort the list of integers sort method does bubble sort on elements.
  • List: 10, 5, 25, 20
  • Compare current item 10 with next 5 if (current > next): current is a large number; else next is a large number. In this case current is a large number so it swaps
  • Now list is 5, 10, 25, 20. It will bubble up elements until it reaches the end of the list.
  • End result: 5, 10, 20, 25
So as you can see ToCompare method returns an int. So if the current value is bigger than the next value it returns 1, else -1. And if both of them are the same then it returns 0
  • 1: swap
  • 0: retain
  • -1: don't swap
What we are achieving in the above code is to sort the list of SmartPhones based on their price.
 
So:
  • if the current price is bigger then next -> return 1
  • if the current price is less then next -> return -1
  • if both are same -> return 0.
Let's check out the output:
 
 
Sorted beautifully.
 

IComparer

 
This is how you can achieve sorting on user-defined classes with the help of the IComparable interface.
 
IComparable is going to help until you have complete control of user-defined class, but let's say you want to apply sorting on a class on which you don't have control.  Meaning you can't change the implementation of a class; e.g., when you access some class from DLL, you can use them but you can't change their implementation.
 
In order to achieve sorting on such classes, the IComparer interface was born.
 
Let's understand this with an example.
 
For Apple, say display was supplied by Sony, which they can assemble in iPhone but Apple can't change the implementation of display..
 
The class display will have the following properties:
  • PPI: Pixel per inch
  • Resolution
  • Size: in inch
  1. public class Display  
  2.    
  3.     public int PPI { getset; }    
  4.     public string Resolution { getset; }    
  5.     public string Size { getset; }    
  6. }   
 Remember Apple cannot make changes in this class. So what Apple does is, they can make a new class, SortDisplay which is going to implement IComparer interface
  •  Sort displays as per PPI.
 Next is SortDisplay class
  1. public class SortDisplay : IComparer<Display>  
  2.    {  
  3.        public int Compare(Display x, Display y)  
  4.        {  
  5.            Display firstDisplay = x as Display;  
  6.            Display secondDisplay = y as Display;  
  7.            return firstDisplay.PPI.CompareTo(secondDisplay.PPI);  
  8.        }  
  9.    } 
  • IComparable has a method named as CompareTo & has only 1 parameter. Because it compares the current object with the next object which is coming as a parameter. Hence current object CompareTo next object.
  • But IComparer has 2 parameters because we are going to pass both of the objects as arguments. Hence method name is Compare: saying Compare the first parameter with the second parameter.
  • While calling the sort function on the list, you have to pass an object of SortDisplay.
  1. class Program  
  2.   {  
  3.       static void Main(string[] args)  
  4.       {  
  5.           List<Display> displays = new List<Display>()  
  6.           {  
  7.               new Display()  
  8.               {  
  9.                   PPI = 224,  
  10.                   Resolution = "1080 * 1920",  
  11.                   Size = "6.1"                      
  12.               },  
  13.               new Display()  
  14.               {  
  15.                   PPI = 300,  
  16.                   Resolution = "1440 * 2180",  
  17.                   Size = "7.1"  
  18.               },  
  19.               new Display()  
  20.               {  
  21.                   PPI = 115,  
  22.                   Resolution = "564 * 900",  
  23.                   Size = "4.2"  
  24.               },  
  25.               new Display()  
  26.               {  
  27.                   PPI = 160,  
  28.                   Resolution = "880 * 980",  
  29.                   Size = "5"  
  30.               }  
  31.           };  
  32.           SortDisplay sorted = new SortDisplay();  
  33.           displays.Sort(sorted);  
  34.           foreach (var item in displays)  
  35.           {  
  36.               System.Console.WriteLine("PPI: "+ item.PPI + " Resolution: "+ item.Resolution +" Size: "+ item.Size);  
  37.           }  
  38.       }  
  39.   } 
Let's see the output.
 
 
There you go, displays are sorted as per PPI.
 

Conclusion

 
In this article, we learned:
  • What are IComparable vs IComparer Interfaces & how to use them.
  • A key difference between these two.
  • When to use which one.
Thank you all.
 
Feel free to connect


Similar Articles