I'm working with a domain model and was thinking about the various ways that we have to implement these two methods in .NET. What is your preferred strategy?
This is my current implementation:
public override bool Equals(object obj) { var newObj = obj as MyClass; if (null != newObj) { return this.GetHashCode() == newObj.GetHashCode(); } else { return base.Equals(obj); } } // Since this is an entity I can use its Id // When I don't have an Id, I usually make a composite key of the properties public override int GetHashCode() { return String.Format("MyClass{0}", this.Id.ToString()).GetHashCode(); }
"If two objects are equal using Object class equals method, then the hashcode method should give the same value for these two objects." So, if in our class we override equals() we should override hashcode() method also to follow this rule.
Since this method is defined in the Object class, hence it is inherited by user-defined classes also. The hashcode() method returns the same hash value when called on two objects, which are equal according to the equals() method. And if the objects are unequal, it usually returns different hash values.
Overriding only equals() method without overriding hashCode() causes the two equal instances to have unequal hash codes, which violates the hashCode contract (mentioned in Javadoc) that clearly says, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two ...
if a class overrides equals, it must override hashCode. when they are both overridden, equals and hashCode must use the same set of fields. if two objects are equal, then their hashCode values must be equal as well. if the object is immutable, then hashCode is a candidate for caching and lazy initialization.
Domain-Driven Design makes the distinction between Entities and Value Objects. This is a good distinction to observe since it guides how you implement Equals.
Entities are equal if their IDs equal each other.
Value Objects are equal if all their (important) constituent elements are equal to each other.
In any case, the implementation of GetHashCode should base itself on the same values that are used to determine equality. In other words, for Entities, the hash code should be calculated directly from the ID, whereas for Value Objects it should be calculated from all the constituent values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With