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?
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
.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With