Difference between IComparable and IComparer

Do you wan to know the difference between IComparable and IComparer! just check my sample below! thanks.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IComparableSamples
{
    /*
     * I hope gives you an idea 
     * what's the difference between the
     * icomparer and icomparable 
     * ----------------------------------------------------------------------
     * IComparable - provides a method of comparing 
     * two objects of a particular type. (in only one way)
     * IComparer - allows you to sort object on different fields combinations
     * so let's start to explore! 
     * sorry for my poor english! :->
     * Mr. Jin Vincent N. Necesario
     * if you think my code needs some improvement please email me at 
     * jin29_neci@hotmail.com, jin29neci@gmail.com thank you!
     */

    class Program
    {
        static void Main(string[] args)
        {
            //let's create some employee's 

            Employee_[] arrOfEmployee = new Employee_[] { 
                new Employee_ ("Michael", "Enriquez", "Calzado",1980),
                new Employee_ ("John", "Chua", "Cruz",1978),
                new Employee_ ("Chris", "Brown","Gold", 2007),
                new Employee_("Cony","JeSan", "Nequez", 2010),
                new Employee_("Johnny","Aban", "Uno", 2006),
            };

            Console.WriteLine("------Unsorted------\n\r");
            
            //let's display the unsorted employee's
            
            foreach (Employee_ emp in arrOfEmployee)
            {
                Console.WriteLine(emp.ReturnFullName);

            }

            Console.WriteLine("\n\r");

            //after creating some employee's let's try to sort the Employe_ class

            Array.Sort(arrOfEmployee);

            Console.WriteLine("------Sorted------\n\r");

            foreach (Employee_ emp in arrOfEmployee)
            {
               Console.WriteLine (emp.ReturnFullName);

            }
            
            Console.WriteLine("\n\r");

            //let's try to reverse the order

            Array.Reverse(arrOfEmployee);

            Console.WriteLine("----Sorted Reverse Order----\n\r");

            foreach (Employee_ emp in arrOfEmployee)
            {
                Console.WriteLine(emp.ReturnFullName);

            }
            Console.WriteLine("\n\r");

            //let's try to sort using the IComparer

            Array.Sort(arrOfEmployee, new ComparerByFullNameWithMiddleName());

            //let's display the unsorted employee's

            Console.WriteLine("----Icomparer Sort Full name with middle name----\n\r");

            foreach (Employee_ emp in arrOfEmployee)
            {
                Console.WriteLine(emp.ReturnFullNameWithMiddleName);

            }
            
            Console.WriteLine("\n\r");
            
            //let's try to sort using the IComparer

            Array.Sort(arrOfEmployee, new ComparerByYearEntry());
            
            Console.WriteLine("----Icomparer Sort Year Entry----\n\r");
            
            foreach (Employee_ emp in arrOfEmployee)
            {
                Console.WriteLine(emp.ReturnFullNameWithMiddleName +" " + emp.ReturnYearEntry );
            }


            Console.ReadKey();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IComparableSamples
{
    class Employee_:IComparable 
    {
        private string strEmployeeFirstName;
        private string strEmployeeLastName;
        private string strEmployeeMiddleName;
        private int intYearEntry;

        public Employee_():this("","","")
        {

        }

        public Employee_(string fName)
        {
            this.strEmployeeFirstName = fName;
        }

        public Employee_(string fName, string lName)
        {
            this.strEmployeeFirstName = fName;
            this.strEmployeeLastName = lName;
        }


        public Employee_(string fName, string lName, string lMName)
        {
            this.strEmployeeFirstName = fName;
            this.strEmployeeLastName = lName;
            this.strEmployeeMiddleName = lMName;
        }


        public Employee_(string fName, string lName, string lMName, int year)
        {
            this.strEmployeeFirstName = fName;
            this.strEmployeeLastName = lName;
            this.strEmployeeMiddleName = lMName;
            this.intYearEntry = year;
        }

        #region Properties

        //returns the employee's fullname
        public string ReturnFullName
        {
            get {
                return string.Concat(this.strEmployeeLastName, ", ", this.strEmployeeFirstName); 
            }
        }

        //returns the employee's fullname with middlename
        public string ReturnFullNameWithMiddleName
        {
            get
            {
                return string.Concat(this.strEmployeeLastName, ", ", this.strEmployeeFirstName, this.strEmployeeMiddleName);
            }
        }

        //returns the employee's fullname with middlinitial
        
        public string ReturnFullNameWithMiddleInitialOnly
        {
            get
            {
                return string.Concat(this.strEmployeeLastName, ", ", this.strEmployeeFirstName, " ", this.strEmployeeMiddleName[0].ToString().ToUpper(), ".");
            }
        }

        public int ReturnYearEntry
        {
            get {
                return this.intYearEntry;
            }
        }

        #endregion 


        #region IComparable Members

        //adds sorting capability to this class

        public int CompareTo(object obj)
        {
            int intRet=0;

            if (obj == null)
                intRet = 1;
            else
            {
                //let's try to cast the object to Employee_; error if the argument is a different type
                Employee_ anotherEmployee = (Employee_)obj;

                //ignore case just compare
                intRet = string.Compare(this.ReturnFullName , anotherEmployee.ReturnFullName, true);
            }

            return intRet;
        }

        #endregion
    }
public class ComparerByFullNameWithMiddleName : IComparer<Employee_>
{
    #region IComparer<Employee_> Members

    int IComparer<Employee_>.Compare(Employee_ emp1, Employee_ emp2)
    {
        return string.Compare(emp1.ReturnFullNameWithMiddleName, emp2.ReturnFullNameWithMiddleName); 
    }

    #endregion
}
public class ComparerByYearEntry : IComparer<Employee_>
{

    #region IComparer<Employee_> Members

    int IComparer<Employee_>.Compare(Employee_ emp1, Employee_ emp2)
    {
        if (emp1.ReturnYearEntry > emp2.ReturnYearEntry)
            return 1;
        if (emp1.ReturnYearEntry < emp2.ReturnYearEntry)
            return -1;
        else
            return 0;
    }

    #endregion
}
}

2 comments:

Anonymous said...

I dosent illustrate internals of these two interfaces....

Please mention the sane

micle said...

Good article its very useful

We can submit .net related article links on http://www.dotnettechy.com to increase the traffic

Post a Comment