Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use IComparable<T> Vs. IComparer<T>

I'm trying to figure out which of these interfaces I need to implement. They both essentially do the same thing. When would I use one over the other?

like image 905
Micah Avatar asked Feb 11 '09 18:02

Micah


People also ask

What is the difference between IComparable and IComparer?

IComparer compares two objects that it's given. IComparable is implemented by the object that is being compared, for the purpose of comparing with another one of itself.

What is the purpose of IComparable interface?

The IComparer interface is used to sort elements that compare two objects and provides additional comparison method.

What is IComparer in C#?

C# IComparer interface The IComparer interface defines a comparison method that a value type or class implements to order or sort its instances. This interface is used with the List. Sort and List. BinarySearch methods. It provides a way to customize the sort order of a collection.

Which of the following method is to be implemented for implementing IComparable interface?

The instance's IComparable implementation is called automatically by methods such as Array. Sort and ArrayList. Sort. The implementation of the CompareTo(Object) method must return an Int32 that has one of three values, as shown in the following table.


2 Answers

Well they are not quite the same thing as IComparer<T> is implemented on a type that is capable of comparing two different objects while IComparable<T> is implemented on types that are able to compare themselves with other instances of the same type.

I tend to use IComparable<T> for times when I need to know how another instance relates to this instance. IComparer<T> is useful for sorting collections as the IComparer<T> stands outside of the comparison.

like image 166
Andrew Hare Avatar answered Sep 20 '22 13:09

Andrew Hare


Use IComparable<T> when the class has an intrinsic comparison.

Use IComparer<T> when you want a comparison method other than the class' intrinsic comparison, if it has one.

like image 35
yfeldblum Avatar answered Sep 21 '22 13:09

yfeldblum