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?
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.
The IComparer interface is used to sort elements that compare two objects and provides additional comparison method.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With