Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Microsoft recommend skip implementing equality operator for reference types?

According to MSDN: Most reference types must not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator.

What is the best practice to implement equals method and equality operator for a typical domain entity like Customer?

Should it implement equals method to return true if identities of two entities are the same? What if entity is not immutable? What if both entities are new and their identities have empty values. And what about equality operator?

As JaredPar mentioned here Equals will actually measure the equality of the values while == will measure whether or not they are the same reference.

like image 623
Jekas Avatar asked Nov 10 '11 07:11

Jekas


2 Answers

Typically I won't implement either (= operator or Equals() for my classes, e.g. Customer).

You definately shouldn't override the = operator because developers using your classes expect = to compare the pointers and not the instances themselves, changing this behaviour will just lead to bugs because people don't expect it to work that way.

If you want to include a way to do a semantic comparison that's what the Equals() method is for, and you can override it to implement the equality check in whatever way makes sense for how you wish to use it in your code.

like image 24
Dylan Smith Avatar answered Sep 22 '22 14:09

Dylan Smith


From MSDN:

Most reference types must not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator.

Microsoft thinks that == should be used only for value-like types, e.g. number types such as Complex, BigInt etc. Composite types such as Person should not override the equality operator. It's a matter of code style and Microsoft merly suggests that you follow this guideline. I doubt that the compiled result will be much different.

like image 95
larsmoa Avatar answered Sep 22 '22 14:09

larsmoa