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):
Depending on the
Equals
method for this object, you may be violating the first point from the documentation as well.More excellent reading