Proper implementation of GetHashCode

I would like to hear from the community how I should implement GetHashCode (or override it) for my object. I understand that I need to do this if I override the equals method. I have implemented it quite a few times, sometimes just calling the base method. I understand that my object must be equal to another instance of the object if it contains the same details (members). What is the best way to get a hash code from class members?

+44
equals c #
Jan 25 '12 at 20:27
source share
1 answer

Let's say your class looks like this:

class Frob { public string Foo { get; set; } public int Bar { get; set; } public double FooBar { get; set; } } 

Let's say you define equals so that two Frob instances are equal if their Foo and their Bar are equal, but FooBar doesn't matter.

Then you must define GetHashCode in terms of Foo and Bar . One of the methods:

 return this.Foo.GetHashCode() * 17 + this.Bar.GetHashCode(); 

Basically, you just want to include all the fields that go into the definition of equality. One way is to just keep accumulating and multiplying by 17, as I did. It is fast, simple, correct and usually gives a good spread.

+34
Jan 25 2018-12-12T00:
source share



All Articles