C# : Equality Operators and Methods for Value Types

Why change operations for equality checking for value types?

  • operator == does not work for value types. : That is why we have to overload the base method for == and !=
  • The Equals method boxes and unboxes values types that causes poor performance.
  • The Equals default method checks each field for equality.

Create our own equality comparison by overload methods for our custom value type classes.

Must do all three of these to keep you class consistent.

  • Override object.Equals : Avoid reflection
  • Implement IEquatable : Avoid unboxing, Make type safe
  • Provide implementation of C#’s == operator

Also override the Object.GetHashCode method, when overriding the Object.Equals method.

  • Override the Object.GetHashCode method

Exmaple Code :

public struct Item : IEquatable<Item> {
    public static bool operator ==(Item lhs, Item rhs){
       return lhs.Equals(rhs);
    }

    public static bool operator !=(Item lhs, Item rhs){
       return !lhs.Equals(rhs);
    }

    public book Equals(Item other){ 
       return this._name == other._name; 
    }

    public override bool Equals(object obj){ 
       if(obj is Item){ 
         return Equals(Item(obj)); 
      } else { 
        return false; 
     }

    public override int GetHashCode(){
        return _name.GetHashCode() ^ _group.GetHashCode();
    }
 } 

}