Implement IComparable interface in C# class

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 4887 red flag

How to implement IComparable interface in our own C# class.

Implement IComparable interface in C# class

In this article we will learn how to implement IComparable interface in our own C# class and what are the advantage on that?  IComparable will allow us to sort object of that class if we implement IComparable interface in it. When a class implements IComparable interface we must add the method CompareTo(T). The T may be any Type.

Implement IComparable

Lets implement IComparable interface in our own class to see how it works? Have a look on below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Reflection;
 
namespace TestDomain
{
    class Person :IComparable<Person>
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int CompareTo(Person tmp)
        {
            //Alphabetic sort if age is equal. [A to Z]
            if (this.Age == tmp.Age)
            {
                return this.Name.CompareTo(tmp.Name);
            }
            //Default to Age sort. [High to low]
            return tmp.Age.CompareTo(this.Age);
        }
 
        public override string ToString()
        {
            //String representation.
            return this.Age.ToString() + "," + this.Name;
        }
    }
    class Program
        {
            public static void Main(String[] args)
            {
 
                List<Person> list = new List<Person>();
                list.Add(new Person() { Name = "Ram", Age =50});
                list.Add(new Person() { Name = "Shyam", Age =60 });
                list.Add(new Person() { Name = "Jadu", Age =30 });
                list.Add(new Person() { Name = "Hari", Age =80 });
                list.Add(new Person() { Name = "Martin", Age =70 });
 
                //Uses IComparable.CompareTo() internally
                list.Sort();
 
                //Uses Person.ToString
                foreach (var element in list)
                {
                    Console.WriteLine(element);
                }
 
                Console.ReadLine();
            }
        }
}

Here is sample output.


So, In output we are seeing that the list has sorted according to Age, (Descending order) . The question is how it has done? Where we did not write any logic for sorting operation?  

In Person class we have implemented IComparable interface like below

Class Person : IComparable<Person>

The IComparable interface is parameterized interface (or generic interface) and it takes parameter T (means any type). We are passing Person class as parameter because we want to implement it in Person class and want to sort object of Person class.

The person class is very simple it contains only two properties those are Name and Age. Here we want to sort collection of Person class according to their Age. As we have discussed earlier we have to define CompareTo function if we want to implement IComparable interface in our own class.

public int CompareTo(Person tmp)
        {
            //Alphabetic sort if age is equal. [A to Z]
            if (this.Age == tmp.Age)
            {
                return this.Name.CompareTo(tmp.Name);
            }
            //Default to Age sort. [High to low]
            return tmp.Age.CompareTo(this.Age);
        }
 

The return type of CompareTo function is integer and parameter type is T. We have define the logic that if two person has same age then use their name to sort otherwise it will sort according to Age.

Within Main() function we are creating List of Person class and calling Sort() method which calls CompareTo() method internally. If we want to change the order, means want to sort in ascending order then we have to make change in CompareTo() method. This is the method to show data in ascending order by Age.

public int CompareTo(Person tmp)
        {
            //Alphabetic sort if age is equal. [A to Z]
            if (this.Age == tmp.Age)
            {
                return tmp.Name.CompareTo(this.Name);
            }
            //Default to Age sort. [High to low]
            return this.Age.CompareTo(tmp.Age);
        }

Here is output


Conclusion:-

In this article we have implemented IComparable interface in our own C# class. Hope you have understood then advantage of IComparable interface.


Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)