What's the best strategy for Equals and GetHashCode?
.net, c#, equals, gethashcode
Solution
Assuming that the instances are equal because the hash codes are equal is wrong.
I guess your implementation of GetHashCode is OK, but I usually use things similar to this:
public override int GetHashCode() {
return object1.GetHashCode ^ intValue1 ^ (intValue2 << 16);
}
Problem
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(); } ```
Related problems
- Best way to compare two complex objects
- Implementing DDD Entity class in C#
- What is the best algorithm for overriding GetHashCode?
- Why is it important to override GetHashCode when Equals method is overridden?
- Is there a way to automatically generate equals and hashcode method in Visual Studio
- Should DDD entities compare by reference or by ID?