Sunday, 19 February 2012

How to Implement IComparable in our custom types?

Yes,we seen in previous article we discussed how to use IComparable interface method of CompareTo() method.with some premitive type.
we not Implemented this IComparable Interface.why because this is already implemented by all primitive types.
but now our Custom type(Employee) we have to implement it. then only we can compare two objects.

Ex :

   class Employee : IComparable
    {
        int eid;

        public int Eid
        {
            get { return eid; }
            set { eid = value; }
        }
        string ename;

        public string Ename
        {
            get { return ename; }
            set { ename = value; }
        }
        string eaddress;

        public string Eaddress
        {
            get { return eaddress; }
            set { eaddress = value; }
        }
     public int CompareTo(object obj)
        {
            Employee eobj = (Employee)obj;
           
            if (this.Eid == eobj.Eid && this.Ename == eobj.Ename && this.Eaddress == eobj.Eaddress)
            {
                return 0;
            }        
            else if (this.Eid.CompareTo(eobj.Eid) == 1 || this.Ename.CompareTo(eobj.Ename) == 1 || this.Eaddress.CompareTo(eobj.Eaddress) == 1)
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }      
        }
    }

now we also impliments  IComparable by Employee type also so we can compare objects of Employee also
so
   class CompareInterfaceDemo
    {          
        static void Main()
        {           
            Employee eobj1 = new Employee();
            eobj1.Eid = 101;
            eobj1.Ename = "kasi";
            eobj1.Eaddress = "hyd";
            Employee eobj2 = new Employee();
            eobj2.Eid = 102;--------------------->different value
            eobj2.Ename = "kasi";
            eobj2.Eaddress = "hyd";
            int i=eobj1.CompareTo(eobj1);-------------------returns 0[zero] 
            int j=eobj1.CompareTo(eobj2);-------------------returns -1[minus one]
             Console.WriteLine(i);
             Console.WriteLine(j);
             Console.Read();
         }

No comments:

Post a Comment