VarunKrish

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.

Exit mobile version