1
votes

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 Answers

2
votes

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