Search code examples
c#.netequalsgethashcode

Is there any negative consequence in having Equals based on GetHashCode?


Is the following code OK?

public override bool Equals(object obj)
{
  if (obj == null || !(obj is LicenseType))
    return false;
  return GetHashCode() == obj.GetHashCode();
}

public override int GetHashCode()
{
  return
    Vendor.GetHashCode() ^ 
    Version.GetHashCode() ^ 
    Modifiers.GetHashCode() ^ 
    Locale.GetHashCode();
}

All the properties are enums/numeric fields, and are the only properties that define the LicenseType objects.


Solution

  • No, the documentation states very clearly:

    You should not assume that equal hash codes imply object equality.

    Also:

    Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality

    And:

    Caution:

    • Do not test for equality of hash codes to determine whether two objects are equal. (Unequal objects can have identical hash codes.) To test for equality, call the ReferenceEquals or Equals method.