icomparer


The IComparer and IComparable interfaces are used for comparing items to provide the ability to sort.

The IComparable interface is mainly used to perform simple sorts on custom objects.

The IComparer interface is used to perform more complex sorting.

The IComparable interface is implemented by the Enum class, the String class, and the Version class.

Objects that implement the IComparable interface must extend the CompareTo method.  This method compares the object that calls it to the object that is passed as a parameter.  The object passed as a parameter must be of the same type as the object calling the CompareTo method.  The return (int) can either be negative (less than the object parameter), zero (same as the object parameter) or positive (greater than the object parameter).

int CompareTo( object objectToCompare );

Here is an example of implementing the IComparable interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NTierWeb.Pages
{
    public class TestComparable : IComparable
    {     

        protected int _testComparableVal;

        public int TestComparableVal
        {
            get
            {
                return _testComparableVal;
            }
            set
            {
                _testComparableVal = value;
            }
        }


        public int CompareTo(object obj)
        {
            if (obj is TestComparable)
            {
                TestComparable tc = (TestComparable)obj;

                return _testComparableVal.CompareTo(tc._testComparableVal);
            }

            throw new ArgumentException("object is not TestComparable");
        }       
    }
}

This is some code to test the TestComparable class:

protected void Page_Load(object sender, EventArgs e)
{
    TestComparable TestComp1 = new TestComparable();
    TestComp1.TestComparableVal = 5;

    TestComparable TestComp2 = new TestComparable();
    TestComp2.TestComparableVal = 6;

    int CompareResult = TestComp1.CompareTo(TestComp2);                                       

}

Here is the testing of the TestComparable class.  As you can see, I created two objects of type “TestComparable” and assigned each a different value.

Then I call The CompareTo method from object1 (value = 5) and pass it object2(value = 6)

image

Then as I step into object1’s CompareTo method, you can see that it checks to make sure the parameter object is of the same type before proceeding with the comparison.

image

Finally, the CompareTo method returns –1 because the parameter is greater than the object itself.  If it had been less then it would have returned a “1”.  If they had been equal it would have returned a 0.

image

No comments:

Post a Comment