I'm trying to implement GetHashCode for an object that I have overridden Equals on.
public override bool Equals(object obj)
{
var myobject = obj as MyObject;
if (myobject == null)
return false;
if (myobject.SomeProperty == null || SomeProperty == null)
return false;
// All default SomeProperty's are equal
if (myobject.SomeProperty.IsDefault)
return SomeProperty.IsDefault;
// Otherwise equality is based on ID
return myobject.SomeProperty.ID == SomeProperty.ID;
}
public override int GetHashCode()
{
if (SomeProperty != null && SomeProperty.IsDefault)
return 0;
else return base.GetHashCode();
}
Is this a reasonable way to do it, or is it likely to cause collisions with base.GetHashCode()?
EDIT: I appreciate the solutions given thus far, but the same question remains. If I do not implement a complete GetHashCode and rely on some other implementation, either base.GetHashCode(), or Guid.GetHashCode(), is there a chance for hash code collisions with the hardcoded 0 value? And if so, is there a simple way to avoid it?