1

Link:

• Consider overriding Equals on a reference type if the semantics of the type are based on the fact that the type represents some value(s).

• 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.

a) To my understanding, for different instances of a reference type to be interchangeable, we should override both Equals method and the equality operator and also make the type immutable?

b) Doesn't a reference type having value semantics suggest that different instances ( that represent the same value ) of that type should be interchangeable?

c) But according to above quote, certain reference types with value semantics should only have Equals method overridden, but not also the equality operator. How can we claim such types have value semantics, since instances of that type are obviously not interchangeable?

d) So based on what criteria do we decide whether a reference type with value semantics should only have its Equals method overridden or also its equality operator? Simply based on whether or not we're willing to make the type immutable?

thanx

1

1 Answer 1

2

Regarding point A, yes, the type ought to be immutable. From MSDN:

You should not override Equals on a mutable reference type.

I think that D is the core question here, and the framework design guidelines seem to indicate that this comes down to performance:

AVOID overloading equality operators on reference types if the implementation would be significantly slower than that of reference equality.

Eric Lippert has some interesting things to say about this here. My favorite quote from it is:

The long answer is that the whole thing is weird and neither works the way it ideally ought to.

Personally this lets me breathe a sigh of relief, as I have always been of the opinion that "==" is functionally a readable shorthand for Equals() (even though I know it isn't).

Sign up to request clarification or add additional context in comments.

2 Comments

Note that there can be occasional times where you want to perform a comparison of the values of a mutable reference type. To address those issues you can use an IEqualityComparer for that type with value semantics, if it's appropriate to use that in a particular context.
so how often we need different values ( and thus need to replace one value object with another ) plays no importance in the decision, even if object creation is expensive? Similarly, does it perhaps also depend on the design technique we're using ( such as Domain Driven Design )?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.