My understanding of these three was:
-
.Equals()tests for data equality (for the lack of a better description)..Equals()can return True for different instances of the same object, and this is the most commonly overridden method. -
.ReferenceEquals()tests whether or not two objects are the same instance and cannot be overridden. -
==is the same as theReferenceEquals()by default, but this CAN be overridden.
But C# station states:
In the object class, the
Equalsand
ReferenceEqualsmethods are
semantically equivalent, except that
theReferenceEqualsworks only on
object instances. The
ReferenceEqualsmethod is static.
Now I don’t get it. Can anyone shed some light on this?
The source of your confusion appears to be that there is a typo in the extract from C# station, which should read: “… except that the Equals works only on object instances. The ReferenceEquals method is static.”
You are loosely correct about the differences in the semantic meanings of each (although “different instances of the same object” seems a little confused, it should probably read “different instances of the same type) and about which can be overridden.
If we leave that aside, let’s deal with the last bit of your question, i.e. how they work with plain
System.Objectinstances andSystem.Objectreferences (we need both to dodge the non-polymorphic nature of==). Here, all three operations will work equivalentally, but with a caveat:Equalscannot be invoked onnull.Equalsis an instance method that takes one parameter (which can benull). Since it is an instance method (must be invoked on an actual object), it can’t be invoked on anull-reference.ReferenceEqualsis a static method that takes two parameters, either / both of which can benull. Since it is static (not associated with an object instance), it will not throw aNullReferenceExceptionunder any circumstances.==is an operator, that, in this case (object), behaves identically toReferenceEquals. It will not throw aNullReferenceExceptioneither.To illustrate: