I overrode the Equals() of my class to compare ID values of type Guid.
Then Visual Studio warned:
... overrides Object.Equals(object o) but does not override Object.GetHashCode()
So I then also overrode its GetHashCode() like this:
public partial class SomeClass { public override bool Equals(Object obj) { //Check for null and compare run-time types. if (obj == null || this.GetType() != obj.GetType()) return false; return this.Id == ((SomeClass)obj).Id; } public override int GetHashCode() { return this.Id.GetHashCode(); } }
It seems to work. Have I done this correctly? Remember Id is of type Guid. Does it matter that my class is an Entity Framework object?
It's my understanding that the original GetHashCode() returns the memory address of the object, so it's essential to override it if you wish to compare two different objects.
If you're implementing a reference type, you should consider overriding the Equals method if your type looks like a base type, such as Point, String, BigNumber, and so on. Override the GetHashCode method to allow a type to work correctly in a hash table.
GetHashCode method of the base class, which computes a hash code based on an object's reference; for more information, see RuntimeHelpers. GetHashCode. In other words, two objects for which the ReferenceEquals method returns true have identical hash codes. If value types do not override GetHashCode, the ValueType.
Your IEquatable<T>. Equals implementation should return results that are consistent with Equals. If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override the Equals(Object) method to return the same result as the equality operator.
As others have said, the use of Reflection in Equals seems dodgy. Leaving that aside, let's concentrate on GetHashCode.
The primary rule for GetHashCode that you must not violate is if two objects are equal then they must both have the same hash code. Or, an equivalent way of saying that is if two objects have different hash codes then they must be unequal. Your implementation looks good there.
You are free to violate the converse. That is, if two objects have the same hash code then they are permitted to be equal or unequal, as you see fit.
I am assuming that "Id" is an immutable property. If "Id" can change over the lifetime of the object then you can have problems when putting the object in a hash table. Consider ensuring that only immutable properties are used in computing equality and hash code.
Your implementation looks good but the fact that you are asking the question indicates that you might not have a solid grasp of all the subtle factors that go into building an implementation of GetHashCode. A good place to start is my article on the subject:
http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/
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