IComparable Interface to sort objects

Was trying Interfaces in .Net . Had a necessity to sort a set of Objects based on a criteria. The IComparable interface comes to the rescue. You can inherit the ICompable interface like this

public class ClassName: IComparable

private string m_Name;

public int Length = 0;

public string Name {

get { return m_Name; }

set { m_Name = value; }


I need to add a CompareTo method also in the class.

public int CompareTo (object obj) {

ClassName cls= (ClassName) obj;

return this.Name.CompareTo (ClassName) .Name);


Now I can use a Array.Sort method on the Array of objects based on the criteria Name.

Published by

Varun Krish

Varun Krish has been dabbling with computers and websites for almost 2 decades. He has traveled to over 30 countries and hopes to visit every country on earth one day. He is currently the Editor-in-Chief of FoneArena.com and also advises startups and product companies on how to build better products. You can follow him on @varunkrish

Leave a Reply

Your email address will not be published.