I found an implementation of GetHashCode() that looks like this
Guid _hashCode = Guid.NewGuid();
public override int GetHashCode()
{
return _hashCode.GetHashCode();
}
Even thought the Equals looks correct, is it correct to say this implementation will cause many assumptions about .NET to break?
public override bool Equals(object obj)
{
if (obj.GetType() != trustedEntity.GetType())
return false;
TrustedEntity typedObj = (TrustedEntity)obj;
if (trustedEntity.BackTrustLink != typedObj.BackTrustLink)
return false;
if (trustedEntity.ForwardTrustLink != typedObj.ForwardTrustLink)
return false;
if (trustedEntity.EntryName != typedObj.EntryName)
return false;
return true;
}
The counter argument I'm hearing is that GetHashCode needs to never change once the object is created. This is because this object is stored in a dictionary.
Can someone clear this up for me and explain what needs to happen to GetHashCode if the object changes, that ultimately changes the Equals method?
From MSDN (Notes to Implementers section):
A hash function must have the following properties:
If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.
The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
For the best performance, a hash function must generate a random distribution for all input.
Depending on the Equals
method for this object, you may be violating the first point from the documentation as well.