Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why overriding == must override equals? [duplicate]

Tags:

c#

.net

Possible Duplicate:
Is it necessary to override == and != operators when overriding the Equals method? (.NET)

C# compiler prompts me that I should override equals if overriding ==, I just want to know why?

like image 494
Adam Lee Avatar asked Nov 16 '12 10:11

Adam Lee


2 Answers

If you are re-defining equality via ==, it gets really confusing if == does something very different to .Equals, and .Equals has to be the fallback because when the type is not known at compile time, only .Equals is available. As a consequence, defining == really means: defining ==, !=, Equals and GetHashCode, and possibly implementing IEquatable<T> for some T.

like image 147
Marc Gravell Avatar answered Sep 28 '22 09:09

Marc Gravell


Because otherwise you'll have two semantically similar operations potentially yielding different results, meaning a lot of confusion.

I'm not sure if the compiler stops you or if it is just a warning, but in either case it's usually good to make sure they behave the same.

There is something like this with double.NaN == double.NaN versus double.NaN.Equals(double.NaN).

like image 34
Adam Houldsworth Avatar answered Sep 28 '22 07:09

Adam Houldsworth