views:

740

answers:

2

With NHibernate entities, you are meant to override Equals and GetHashCode. Is it a good idea to override the == operator to use the .Equals implementation also?

+4  A: 

Yes, it is a more general .NET "best practice" to keep Equals(), operator== and GethasCode() consistent.

See Guidelines for Overloading Equals() and Operator == .

Henk Holterman
A: 

Why do you believe you need to override Equals and GetHashCode when using NHibernate? NHibernate guarantees entity equality for any entity accessed in the same ISession. See Considering object identity in the documentation.

Edited to add: After re-reading the question and doing some googling, I have to admit I had no idea that the equality operator (==) could be overridden in C#.

Jamie Ide
1. You might want to ignore persistence at all. That's why we use ORM in the first place.2. It is rather strange when 2 instances of the same entity are not equal.3. You want to be able to use collections like sets4. You want your code to behave the same way without NHibernate. That means that you cannot rely on the identitymap in ISession
Paco
Do you disagree with my point that NHibernate does not require you to implement Equals and GetHashCode? That was the question, was it not? Whether it's a best practice in general (imo: yes for value types, maybe for reference types) is a different question.
Jamie Ide
Reasons for overriding Equals and GetHashCode are linked from http://www.derickbailey.com/2008/03/24/NHibernateBestPracticesALWAYSOverrideEqualsAndGetHashCode.aspx
mcintyre321
Take a look at the comments -- he's declaring it a best practice for objects that will be used across ISessions or in collections. My point is that there is nothing specific to NHibernate that requires you to override Equals and GetHashCode as a best practice. The reasons to do it are the same as they are for any object.
Jamie Ide
If you look in the official NHibernate docs is strongly recommended to override equals/hashcode...
andrew007
Only if you need equality for objects loaded from different ISessions: "This only applies if these objects are loaded in two different ISessions, as NHibernate only guarantees identity ( a == b , the default implementation of Equals()) inside a single ISession!" (http://knol.google.com/k/fabio-maulo/nhibernate-chapter-4-persistent-classes/1nr4enxv3dpeq/7#4%282E%293%282E%29%28C2%29%28A0%29Implementing_Equals%2828%29%2829%29_and_GetHashCode%2828%29%2829%29)
Jamie Ide