What needs to be overridden in a struct to ensure equality operates properly?

Viewed 44515

As the title says: do I need to override the == operator? how about the .Equals() method? Anything I'm missing?

6 Answers

Unfortunetely I don't have enough reputation to comment other entries. So I'm posting possible enhancement to the top solution here.

Correct me, if i'm wrong, but implementation mentioned above

public struct Complex 
{
   double re, im;
   public override bool Equals(Object obj) 
   {
      return obj is Complex && this == (Complex)obj;
   }
   public override int GetHashCode() 
   {
      return re.GetHashCode() ^ im.GetHashCode();
   }
   public static bool operator ==(Complex x, Complex y) 
   {
      return x.re == y.re && x.im == y.im;
   }
   public static bool operator !=(Complex x, Complex y) 
   {
      return !(x == y);
   }
}

Has major flaw. I'm refering to

  public override int GetHashCode() 
   {
      return re.GetHashCode() ^ im.GetHashCode();
   }

XORing is symmetrical, so Complex(2,1) and Complex(1,2) would give same hashCode.

We should probably make something more like:

  public override int GetHashCode() 
   {
      return re.GetHashCode() * 17 ^ im.GetHashCode();
   }
Related