I blogged last year last year about Overriding Equals and GetHashCode.
You provide an Equals override if you want to provide value equality on your business objects and normally, you'd use the logical key fields (DB lingo) for comparison.
GetHashCode is used by ISet (ListSet), if you used NHibernate, it'll force you to provide GetHashCode since it uses an object's hashcode as identifier for a set element. So basically if you have two object instances with the same hashcode, they are treated as one.
With the previous post, I raised the question on what is the magic number 29 which is used by Resharper in generating GetHashCode method implementation. Here is a sample code using _id, _category and _expression fields as logical key:
public override int GetHashCode()
{
int result = _id;
result = 29*result + _category.GetHashCode();
result = 29*result + _expression.GetHashCode();
return result;
}
I have just asked JetBrains support on why 29? Here is what I got:
The number 29 is special in a way that it's a simple number, but
other than that, it doesn't have any specific properties and we could use other simple numbers like 31 etc as well. Thank you!
Posted
07-16-2007 5:30 PM
by
jokiz