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.
- Important Interface in .NET: Work with IEnumerable Interface
- 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.
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace SelfHostingWebAPI
- {
- public class Person
- {
- public Int16 ID { get; set; }
- public string name { get; set; }
- public string surname { get; set; }
- }
- class Program
- {
- static void Main(string[] args)
- {
- List<Person> per = new List<Person>()
- {
- new Person{ID=1,name="sourav",surname="kayal"},
- new Person{ID=2,name="Ram",surname="kumar"}
- };
- per.Sort();
- Console.ReadLine();
- }
- }
- }
And here is the output of the above example.

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.



Karan VoraPosted Apr 18, 2018, 7:16 AM
One of the best tutorials on Interfaces in C#. Thanks man!!