views:

105

answers:

2

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 :-).

+6  A: 

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.

Jon Skeet
Nice post! Never really put my finger on it, but indeed - out of tens of classes there may be one where I actually need equality semantics. In those cases it usually is an equality coming from the application specs. In the beginning .NET copied a number of things from JAVA. I wonder what the argument was to 'have' those things in the root of the inheritance tree, other than similarity to the antetype.
flq
Great post! Thank you very much.
macias
+2  A: 

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().

ammoQ
No, I didn't forget this option. If programmer needs reference comparison, she/he should use reference comparison explicitly (ReferenceEquals). IOW -- say what you mean, don't take shortcuts.Typing Equals instead of ReferenceEquals assuming they are equivalent is bad approach (IMHO).
macias