Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange implementation of Object.Equals

Tags:

I was reading the MSDN documentation about object.Equals. in the remarks part it mentioned:

If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result. This means that if objA overrides the Object.Equals(Object) method, this override is called.

My question is why they did not implement this part as objA.Equals(objB) && objB.Equals(objA) to make equality symmetric and just relate on one side of the relation? It can result in strange behaviors when calling object.Equals.

EDIT: Strange behavior can happen when type of objA overrides Equals method and implemented it as something not predictable, but type of objB does not override Equals.

like image 420
alisabzevari Avatar asked Jul 27 '15 05:07

alisabzevari


People also ask

How do you write equal?

Equal is a value or data that's the same or equivalent to another value and is represented by the = symbol. The equal sign symbol shares the same key as the + key on a keyboard and is next to the backspace key.

Which of the following options is the correct signature of the equals () method?

equals(other) could be a solution. And indeed, it usually is the correct solution.


1 Answers

Basically, this would only be of any use to developers with flawed Equals implementations. From the documentation:

The following statements must be true for all implementations of the Equals(Object) method. In the list, x, y, and z represent object references that are not null.

  • [...]
  • x.Equals(y) returns the same value as y.Equals(x).
  • [...]

So the check is redundant in every case where the method has been correctly implemented - causing a performance hit to every developer who has done the right thing.

It isn't even terribly useful to developers who haven't done the right thing, as they may still expect object.Equals(x, y) to return true when it returns false - they could debug and find that their method returns true, after all. You could say that it would be documented to check both ways round - but we've already established that the only developers this affects are ones who don't read the documentation anyway.

Basically, when you override a method or implement an interface, you should know what you're doing and obey the specified contract. If you don't do that, you will get odd behaviour, and I don't think it's reasonable to expect every caller to try to work around implementations which don't do what they're meant to.

like image 74
Jon Skeet Avatar answered Sep 27 '22 22:09

Jon Skeet