Click to See Complete Forum and Search --> : difference between IComparer and IComparable


ricky_cpp
October 9th, 2009, 04:03 AM
Hi all,

It is still not clear to me. Whats the difference between these 2 interfaces.

IComparer uses Compare(objext a, object b) method to sort and IComparable uses CompareTo(object a) method to sort order.

But both of them serve the same purpose. Can anyone please explain why there exists 2 interfaces for serving same puppors.

Regards,
Ricky

vcdebugger
October 9th, 2009, 04:28 AM
the only difference i can make out by seeing them is one takes 2 parameters for comparison and the other one takes only 1 paramater.

someuser77
October 9th, 2009, 04:33 AM
IComparable (http://msdn.microsoft.com/en-us/library/system.icomparable.aspx) is implemented by types that you wish to give them the ability to compare themselves to other instances of the same type, when sorting for example.

IComparer (http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx) is implemented by a type that you wish to use as a sorting predicate when sorting a collection. This allows you to create several classes that will compare the same two instances in different ways thus creating a different sort order.

Array.Sort will use each element's IComparable implementation to sort the values or it can receive an IComparer to choose the order.

For more information read How to use the IComparable and IComparer interfaces in Visual C# (http://support.microsoft.com/kb/320727)

ricky_cpp
October 9th, 2009, 10:30 AM
Hi someuser77,

I am sorry, but I am confused even after seeing the link you sent.

If for e.g. Ihave an object of class Car

public Class Car
{
public string model,
public int make;
}

I have an array of Car objects.

Now what will happen when I implement IComparable?
Will it sort Car objects according to model or according to make?
Will it arrange objects in ascending order or in descending order?

Why/When will I implement IComaprer?

someuser77
October 9th, 2009, 10:52 AM
Now what will happen when I implement IComparable?
Your class will have an IComparable.CompareTo Method (http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx).
Will it sort Car objects according to model or according to make?
Depends on how will you implement the CompareTo method, if you wish they will be sorted by both.
Will it arrange objects in ascending order or in descending order?
Depends on the value returned by the CompareTo method.
Less than zero - This instance is less than obj.
Zero - This instance is equal to obj.
Greater than zero - This instance is greater than obj.
Why/When will I implement IComaprer?
When you will need to implement a special comparer class that will behave differently than the IComparable implementation, for example, if your default implementation compares Cars by model and you wish to compare them by make.

ricky_cpp
October 9th, 2009, 12:04 PM
Thanks someuser77. That was nicely explained.