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

RCIX picture RCIX · Oct 1, 2009 · Viewed 42.1k times · Source

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

Answer

UpTheCreek picture UpTheCreek · Oct 1, 2009

An example from msdn

public struct Complex 
{
   double re, im;
   public override bool Equals(Object obj) 
   {
        return obj is Complex c && this == c;
   }
   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);
   }
}