views:

347

answers:

4

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

+3  A: 

Yes,

== , != , Equals() and don't forget to ensure that GetHashCode() is consistent too.

Henk Holterman
+5  A: 

An example from msdn

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);
   }
}
UpTheCreek
+2  A: 

The basic difference among the two is that the == operator is static, i.e. the appropriate method to invoke is determined at compile time, while the Equals method is invoked dinamically on an instance.
Defining both is probably the best thing to do, even if this matters less in the case of structs, since structs cannot be extended (a struct can't inherit from another).

Paolo Tedesco
+5  A: 

You should also implement IEquatable<T>. Here is an excerpt from Framework Design Guidelines:

DO implement IEquatable on value types. The Object.Equals method on value types causes boxing, and its default implementation is not very effcient because it uses refection. IEquatable.Equals can offer much better performance and can be implemented so that it does not cause boxing.

public struct Int32 : IEquatable<Int32> {
    public bool Equals(Int32 other){ ... }
}

DO follow the same guidelines as for overriding Object.Equals when implementing IEquatable.Equals. See section 8.7.1 for detailed guidelines on overriding Object.Equals

Dzmitry Huba
So this is only used on value types? (not reference?)
UpTheCreek