« Miscellaneous notes on cookies | Main | web.config file syntax documentation »

Equals override

In the body of an override for Equals, the compiler appears to call the base class Object.Equals when comparing members of a class that has its own Equals override. Calling member1.Equals(obj2.member1) calls the override. Very puzzling.

 

The answer is that Object.Equals, operator == and operator != are three separate functions. The debugger’s command window turns a == b into a call to a.Equals(b) rather than operator ==(a,b). Likewise NUnit’s AssertEquals calls the Equals method. But in compiled C# code, using “==” will call the operator == method and not the Equals method. To remain sane, if you override Equals, do it in terms of overridden operator ==. And define operator != in terms of operator ==. Also remember to override GetHashCode.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)