Can someone please explain with example that I can understand about the difference between .Equals, IComparable and IComparer.
I was asked this in an interview.
Can someone please explain with example that I can understand about the difference between .Equals, IComparable and IComparer.
I was asked this in an interview.
Well first off, on the surface, Equals
is a method (present in every object), while IComparable
and IComparer
are interfaces.
Equals
is present in any class and can be overriden to provide equality testing depending on the context of the class (it's a good practice to override GetHashCode
as well). By default it just tests if objects are equal in memory which is not very useful. Equals
(and GetHashCode
) are usually given a different implementation in the context of searching or hashing.
Implementing IComparable
is a more fine-grain way of comparison, as it provides the CompareTo
method, which is a greater-than/less-than comparison as opposed to Equals
which is simply a is-equal-or-not comparison. For example a binary search tree structure could benefit from this method.
IComparer
is similar to IComparable
, except that it works from the outside. It allows you to define a "neutral" object that is used for comparing two other objects without modifying them directly, which you need to do with IComparable
.
Equals
is a method, when 2 other are interfaces. So look like the biggest difference.
More seriously - @ChrisSinclair gave you an answer in comments...
Equals returns true/false if the two objects are equal (or the same reference depending on your implementation) IComparable/IComparer: difference between IComparable and IComparer
.Equals() gives your class a way to test for equality against all other possible objects. This can be considered as the fallback for object equality. So this answers the question am I equivalent to the object passed in as a param.
IComparable provides for a way of comparing objects which can be ordered, possible uses include sorting. Implementing this interface puts the ordering logic into your class.
IComparer does pretty much the same as IComparable except the logic is contained in separate class.