Equality Pattern from Resharper

I was just reading this blog entry on how Resharper can auto generate equality members.

This is a pretty nice pattern to follow even when doing this by hand.

Here is the class it was created for:

public class Fooberry


{


    public string Foo { get; set; }


    public string Bar { get; set; }


}




 





public override bool Equals(object obj) {   


    if (ReferenceEquals(null, obj)) return false;   


    if (ReferenceEquals(this, obj)) return true;   


    if (obj.GetType() != typeof (Fooberry)) return false;   


    return Equals((Fooberry) obj);   


}   


  


public bool Equals(Fooberry obj)   


{   


    if (ReferenceEquals(null, obj)) return false;   


    if (ReferenceEquals(this, obj)) return true;   


    return Equals(obj.Foo, Foo) && Equals(obj.Bar, Bar);   


}   


  


public override int GetHashCode()   


{   


    unchecked  


    {   


        return ((Foo != null ? Foo.GetHashCode() : 0)*397) ^ (Bar != null ? Bar.GetHashCode() : 0);   


    }   


}  




 



I’ve know about most of this pattern including ReferenceEquals, but look at the unchecked keyword.  Very cool indeed.  I do wonder what the significance of the ‘* 397’ is though.  Any ideas?

Post a Comment