For an "easy to understand and efficient" code, i would suggest these simple rules (i may be wrong :) :
1) Never put a persistent object in an ISet before its keys are defined
2) Always use the primary key attributes' GetHashCode and Equals (I know this is supposed to be 'bad' because these values may change but, if you follow the rule #1, it won't break anything)
So let's say you have an Article and its pk is 'Id' (long)
I would create :
Code:
public override bool Equals(object other) {
if (other is Article) {
return Id.Equals(((Article) other).Id);
} else {
return false;
}
}
and
Code:
public override int GetHashCode() {
return Id.ToString().GetHashCode();
}
And if you have a composite pk, let's say an orderLine (bad idea for an order line but just for the example), whose key atributes are : orderId and articleId.
Code:
public override bool Equals(object other) {
if (other is OrderLine) {
return
OrderId.Equals(((OrderLine) other).OrderId)
&& ArticleId.Equals(((OrderLine) other).ArticleId);
} else {
return false;
}
}
and
Code:
public override int GetHashCode() {
return (OrderId.ToString() +"|" + ArticleId.ToString()) .GetHashCode();
}
Finally, I would say that an Equals() method that doesn't reflect the business Equality is definitly wrong and will lead you into errors.
If you want to check the address equality, just compare the instances with the "==" operator.