9
votes

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.

2
The link you've given doesn't show that text for me - can you clarify where it's coming from? (In particular, it uses the word "override" incorrectly near the end, which raises some suspicion...)Jon Skeet
The direct link. See Notes to Implementers.Jekas
The use of the word "must" is odd here too. Sounds like a poorly expressed guideline with no reasoning behind it - IIRC, "Effective C#" and "C# 4 in a Nutshell" both have more discussion on this.Jon Skeet

2 Answers

5
votes

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.

3
votes

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.