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".
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 :)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With