Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Any Code optimization technique for Overriding "Equals"?

Tags:

c#

Normally ( Based on my understanding ) i have to follow a lot of steps to

override the "Equals" to check the state of the object.

Example :

    public override bool Equals(object obj)
     {
       if (obj is SalesPerson && obj != null)
       {

         SalesPerson temp;

         temp = (SalesPerson)obj;

           if (temp.fName == this.fName && temp.lName == this.fName 
              && temp.personAge == this.personAge )
              {

                 return true;
              }

          else
          {
            return false;
          }

      }
       return false;
     }

Any other alternative like LINQ or other techniques gives me shortcut code ?

Update :

Moreover i gusess i have to override GetHasCode() too when i override "Equals".

like image 824
user160677 Avatar asked Nov 28 '22 15:11

user160677


2 Answers

All the answers so far seem mostly fine to me. However, you should carefully consider what you want equality to mean in an inheritance hierarchy. Can an instance of just SalesPerson be equal to an instance of SalesManager (which would derive from SalesPerson)?

The trouble is, the symmetric nature of equals gets in the way. Suppose we have:

SalesPerson x = new SalesPerson { ... };
SalesManager y = new SalesManager { ... };

I'd expect y.Equals(x) to be false - which means that x.Equals(y) ought to be false too.

This means the check in SalesPerson really needs to be:

public override bool Equals(object obj)
{
    SalesPerson salesPerson = obj as SalePerson;
    if (salesPerson == null) return false;
    return salesPerson.GetType() == this.GetType() &&
           salesPerson.fName == this.fName && 
           salesPerson.lName == this.fName && 
           salesPerson.personAge == this.personAge;
}

Note that I'm not comparing with typeof(SalesPerson) as the implementation in SalesManager would probably want to call up to this implementation first.

Of course, all of this complication goes away if SalesPerson is sealed... another reason for being very careful before introducing inheritance :)

like image 80
Jon Skeet Avatar answered Dec 18 '22 00:12

Jon Skeet


This looks neater:

public override bool Equals(object obj)
{
  SalesPerson salesPerson = obj as SalePerson;
  if(salesPerson == null) return false;
  return salesPerson.fName == this.fName && 
         salesPerson.lName == this.fName && 
         salesPerson.personAge == this.personAge;
}
like image 28
Charlie Avatar answered Dec 18 '22 01:12

Charlie