Important Interface in .NET: Work With IComparable Interface

Welcome to the “Important Interface in C#” article series. In this series, we will be talking about various user interfaces of the .NET class library. In our previous article we have talked about the IEnumerable and ICollection interfaces, you can read them here.
  1. Important Interface in .NET: Work with IEnumerable Interface
  2. Important Interface in .NET: Work with ICollection Interface
In this article, we will discuss the IComparable interface in the .NET class library. We know that sorting is very easy when we use a collection with a predefined data type, for example, List<int>(). The Sort() method is available that takes care of sorting.
 
But, how to implement sorting when we work with a user-defined data type or when we want to sort an object on the basis of its property?
 
Let’s try the Sort() method over a collection of user defined objects.
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6.    
  7. namespace SelfHostingWebAPI  
  8. {  
  9.     public class Person  
  10.     {  
  11.         public Int16 ID { getset; }  
  12.         public string name { getset; }  
  13.         public string surname { getset; }  
  14.     }  
  15.     class Program  
  16.     {  
  17.         static void Main(string[] args)  
  18.         {  
  19.             List<Person> per = new List<Person>()  
  20.             {  
  21.                 new Person{ID=1,name="sourav",surname="kayal"},  
  22.                 new Person{ID=2,name="Ram",surname="kumar"}  
  23.             };  
  24.             per.Sort();  
  25.             Console.ReadLine();  
  26.         }  
  27.     }  

And here is the output of the above example.
 
Interface in .NET
 
So, the runtime is saying that it cannot compare two objects because those objects are user-defined and there is no mechanism in the class to compare the two objects.
To solve this problem we will implement an IComparable<T> interface in our class and we will implement the CompareTo() method.
 
Before going to the implementation let’s see what the IComparable <T> interface is and its method and properties.
 
Location of IComparable interface in the .NET class library
 
Namespace: System
Assembly: mscorlib.dll
 
Syntax of IComparable interface
 
Public interface IComparable
In other words, this interface does not implement any other interface.
 
Methods
 
It contains only one method as in the following:
 
CompareTo(): Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
 
Now, let’s implement the IComparable interface in our own class. Have a look at the following example.
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6.    
  7. namespace SelfHostingWebAPI  
  8. {  
  9.     public class Person : IComparable<Person>  
  10.     {  
  11.         public Int16 ID { getset; }  
  12.         public string name { getset; }  
  13.         public string surname { getset; }  
  14.    
  15.         public int CompareTo(Person other)  
  16.         {  
  17.             if (this.ID > other.ID)  
  18.                 return 1;  
  19.             else if (this.ID < other.ID)  
  20.                 return -1;  
  21.             else  
  22.                 return 0;  
  23.         }  
  24.     }  
  25.     class Program  
  26.     {  
  27.         static void Main(string[] args)  
  28.         {  
  29.             List<Person> per = new List<Person>()  
  30.             {  
  31.                 new Person{ID=3,name="sourav",surname="kayal"},  
  32.                 new Person{ID=1,name="Ram",surname="kumar"},  
  33.                 new Person{ID=2,name="Sudip",surname="Das"}  
  34.             };  
  35.             //Apply sort method in user defined object's collection  
  36.             per.Sort();  
  37.    
  38.             foreach (Person p in per)  
  39.             {  
  40.                 Console.WriteLine(p.ID + " " + p.name + "  " + p.surname);  
  41.             }  
  42.             Console.ReadLine();  
  43.         }  
  44.     }  

And here is my ordered list depending on the roll number.
 
Interface in .NET
 
In the above example, we were returning the values 0,1 and -1 depending on the comparison. If we do not return any value then it will return the value different from the two properties of the objects. Have a look at this example. Here we are comparing the salary property of two objects.
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6.    
  7. namespace SelfHostingWebAPI  
  8. {  
  9.     public class Person : IComparable  
  10.     {  
  11.         public string name { getset; }  
  12.         public Int16 SalaryAmount { getset; }  
  13.    
  14.         public int CompareTo(object obj)  
  15.         {  
  16.             if (obj == this)  
  17.                 return 1;  
  18.             else  
  19.                 return this.SalaryAmount.CompareTo(this.SalaryAmount);  
  20.         }  
  21.     }  
  22.     class Program  
  23.     {  
  24.         static void Main(string[] args)  
  25.         {  
  26.             Person p1 = new Person();  
  27.             p1.name = "Sourav";  
  28.             p1.SalaryAmount = 1500;  
  29.    
  30.             Person p2 = new Person();  
  31.             p2.name = "Ram";  
  32.             p2.SalaryAmount = 1000;  
  33.             Console.WriteLine("Diffrence between salary of p1 and p2");  
  34.             Console.WriteLine(p1.SalaryAmount.CompareTo(p2.SalaryAmount));  
  35.             Console.ReadLine();  
  36.         }  
  37.     }  

And the salary difference of p1 and p2 is 500.
 
Interface in .NET
 

Conclusion

 
In this article, we have learned to work with the IComparable interface in the .NET class library. This interface is really helpful for implementing a sorting mechanism in our custom object collection. I hope those examples helped you. In a future article, we will focus on a few more helpful interfaces in the .NET class library.


Similar Articles