Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 276
RCIX Avatar asked Oct 01 '09 07:10

RCIX


People also ask

Should I override equality and inequality operators?

In a class, if you overload the Equals method, you should overload the == and != operators, but it is not required.

How do you override equals method in C#?

Because Complex is a value type, it cannot be derived from. Therefore, the override to Equals(Object) method need not call GetType to determine the precise run-time type of each object, but can instead use the is operator in C# or the TypeOf operator in Visual Basic to check the type of the obj parameter.


2 Answers

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);    } } 
like image 177
UpTheCreek Avatar answered Oct 13 '22 02:10

UpTheCreek


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

like image 20
Dzmitry Huba Avatar answered Oct 13 '22 02:10

Dzmitry Huba