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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well first off, on the surface,
Equalsis a method (present in every object), whileIComparableandIComparerare interfaces.Equalsis 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 overrideGetHashCodeas well). By default it just tests if objects are equal in memory which is not very useful.Equals(andGetHashCode) are usually given a different implementation in the context of searching or hashing.Implementing
IComparableis a more fine-grain way of comparison, as it provides theCompareTomethod, which is a greater-than/less-than comparison as opposed toEqualswhich is simply a is-equal-or-not comparison. For example a binary search tree structure could benefit from this method.ICompareris similar toIComparable, 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 withIComparable.