Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best strategy for Equals and GetHashCode?

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(); } 
like image 238
tucaz Avatar asked Mar 02 '10 12:03

tucaz


People also ask

When should we override hashCode and equals?

"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.

How do we implement hashCode () and equals ()?

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.

Is it necessary to override hashCode and equals method?

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 ...

What are equals () and hashCode () overriding rules?

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.


1 Answers

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.

like image 181
Mark Seemann Avatar answered Sep 18 '22 04:09

Mark Seemann