Welcome to the “Important Interface in C#” article series. In this series we will be talking about various useful 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 it’s 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 it’s 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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SelfHostingWebAPI
{
public class Person : IComparable<Person>
{
public Int16 ID { get; set; }
public string name { get; set; }
public string surname { get; set; }
public int CompareTo(Person other)
{
if (this.ID > other.ID)
return 1;
else if (this.ID < other.ID)
return -1;
else
return 0;
}
}
class Program
{
static void Main(string[] args)
{
List<Person> per = new List<Person>()
{
new Person{ID=3,name="sourav",surname="kayal"},
new Person{ID=1,name="Ram",surname="kumar"},
new Person{ID=2,name="Sudip",surname="Das"}
};
//Apply sort method in user defined object's collection
per.Sort();
foreach (Person p in per)
{
Console.WriteLine(p.ID + " " + p.name + " " + p.surname);
}
Console.ReadLine();
}
}
}
And here is my ordered list depending on roll number.
In the above example we were returning the values 0 ,1 and -1 depending on 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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SelfHostingWebAPI
{
public class Person : IComparable
{
public string name { get; set; }
public Int16 SalaryAmount { get; set; }
public int CompareTo(object obj)
{
if (obj == this)
return 1;
else
return this.SalaryAmount.CompareTo(this.SalaryAmount);
}
}
class Program
{
static void Main(string[] args)
{
Person p1 = new Person();
p1.name = "Sourav";
p1.SalaryAmount = 1500;
Person p2 = new Person();
p2.name = "Ram";
p2.SalaryAmount = 1000;
Console.WriteLine("Diffrence between salary of p1 and p2");
Console.WriteLine(p1.SalaryAmount.CompareTo(p2.SalaryAmount));
Console.ReadLine();
}
}
}
And the salary difference of p1 and p2 is 500.
Conclusion:
In this article we have learned to work with the IComparable interface in the .NET class library. This interface is realy 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.