Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of making Equals a common method?

This is not a question how to implement it but what is the purpose of this method? I mean -- OK, I understand that is needed when searching, but why it is buried as an method of "object" class?

The story goes -- I have classes which objects are not comparable by default (in logical sense). Each time you want to compare/search for them you have to specify exactly how matching is done. The best in such case would be:

  1. there is no such ubiquitous method as Equals, problem solved, no programmer (user of my class) would fall in trap by omitting custom match when searching

    but since I cannot change C#

  2. hide inherited, unwanted methods to prevent the call (compile-time)

    but this also would require change to C#

  3. override Equals and throw exception -- at least programmer is notified in runtime

So I am asking because I am forced to ugly (c), because (b) is not possible and because of lack of (a).

So in short -- what is the reason of forcing all objects to be comparable (Equals)? For me it is one assumption too far. Thank you in advance for enlightenment :-).

like image 596
greenoldman Avatar asked Dec 03 '09 08:12

greenoldman


2 Answers

I agree that it was basically a mistake, in both .NET and Java. The same is true for GetHashCode - along with every object having a monitor.

It made a bit more sense before generics, admittedly - but with generics, overriding Equals(object) always feels pretty horrible.

I blogged about this a while ago - you may find both the post and the comments interesting.

like image 117
Jon Skeet Avatar answered Sep 26 '22 14:09

Jon Skeet


You forgot option 4.: Do nothing, let the default reference equality take place. No big deal IMO. Even with your custom match options, you could choose a default option (I'd go for the most strict option) and use it to implement Equals().

like image 44
Erich Kitzmueller Avatar answered Sep 26 '22 14:09

Erich Kitzmueller