Thursday, July 1, 2010

IMPLEMENTING ICOMPARABLE INTERFACE

Array of types that support IComparer, you can sort that array without providing any explicit reference to IComparer. In that case, the elements of the array are cast to the default implementation of IComparer . However, For sorting or comparison capability for custom objects It can be used.

Its works under System.Collections Namespace

IComparable
The role of IComparable is to provide a method of comparing two objects of a particular type.

Example Programe

using System;
class combo:IComparable
{
public int id;
public string name;
public combo(string name1,int x)
{
name=name1;
id=x;
}
public int CompareTo(object o)
{
combo temp=(combo) o;
if(this.id>temp.id)
return (1);
if(this.idreturn (-1);
else
return (0);
}
}
class icomparable
{
public static void Main(string[] args)
{
combo[] c=new combo[3];
c[0]=new combo("aaa",123);
c[1]=new combo("bbb",12);
c[2]=new combo("ccc",1);
Array.Sort(c);
foreach(combo m in c)
Console.WriteLine(m.name+"\t"+m.id);
}
}

No comments:

Post a Comment