Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ReferenceEquals - true and Equals - false expected behaviour?

Tags:

c#

If object.ReferenceEquals returns true, should instance.Equals always return true?

Would you think its unexpected behaviour where the output below was pass/fail?

Assert.True(object.ReferenceEquals(obj,obj));
Assert.True(obj.Equals(obj));

Personally I think its strange, and cant really think of a good reason, where an instance should not be equal to itself.

like image 737
jasper Avatar asked Jun 05 '26 08:06

jasper


2 Answers

There are two ways to answer your question.

  • It's unexpected behavior, yes. A properly-designed class should always return true from .Equals if it returns true from .ReferenceEquals. That's codified in MSDN's Design Guidelines for Developing Class Libraries, Implementing the Equals Method article:

    Follow the contract defined on the Object.Equals Method as follows:
         x.Equals(x) returns true.

  • But that requirement is not enforced by the language or runtime. The designer of the class in question is perfectly free to define Equals as { return false; }. Perverse, but possible.

like image 115
Michael Petrotta Avatar answered Jun 07 '26 21:06

Michael Petrotta


Yes, if reference equals is true, proper implementation of equals should return true.

like image 32
manojlds Avatar answered Jun 07 '26 22:06

manojlds