Alex Rivera | Logout

Using GetHashCode to test equality in Equals override

Asked 2010-11-22T18:50:52.077
11

Is it ok to call GetHashCode as a method to test equality from inside the Equals override?

For example, is this code acceptable?

public class Class1
{
  public string A
  {
    get;
    set;
  }

  public string B
  {
    get;
    set;
  }

  public override bool Equals(object obj)
  {
    Class1 other = obj as Class1;
    return other != null && other.GetHashCode() == this.GetHashCode();
  }

  public override int GetHashCode()
  {
    int result = 0;
    result = (result ^ 397) ^ (A == null ? 0 : A.GetHashCode());
    result = (result ^ 397) ^ (B == null ? 0 : B.GetHashCode());
    return result;
  }
}
Edit
Report

1 Answer

7

No, it is not ok, because it's not

equality <=> hashcode equality.

It's just

equality => hashcode equality.

or in the other direction:

hashcode inequality => inequality.

Quoting http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx:

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.

answered 2010-11-22T18:55:20.747

Your Answer