C# : Override Operators == and != along with .Equals : Reference Types

When comparing “reference” types in c# with operators == and !=, we should overwrite these operators to perform comparison checks on the reference type’s specific value field or multiple fields. C# provides operators == and != to compare reference types by checking if they point to the same object in memory versus comparing if the two objects are equal. If we would like to design our comparison operators of == and != to return a comparison of the objects specific field then we must overwrite the operators our self.

Best Practice

** Overwrite the Equals method from the base class “Object” as well. This will keep the equality operators in sync for other developers that may use your class and its compare features. It is also best practice to always use the “Equals” method to check the equality of any reference type. Using operators causes issues when using generics.

private string _name;

public static bool operator == (Product prod1, Product prod2)
{
    if(prod1.Name.Equals(prod2.Name)){
        return true;
    } else {
        return false;
    }
}

public static bool operator != (Product prod1, Product prod2)
{
    if(!prod1.Name.Equals(prod2.Name)){
        return true;
    } else {
        return false;
    }
}

public overwrite bool Equals(Product first, Product second)
{
   if(first == null || second == null){
     return false;
   }

   if(first.Name == second.Name){
     return true;
   } else {
     return false;
   }
}

public string Name {
    get {
        return _name;
    }
    set {
        this._name = value.ToUpper();
    }
}