Implementing GetHashCode correctly

C#.NetEquals

C# Problem Overview


I'd like to hear from the community on how I should go about implementing GetHashCode (or override it) for my object. I understand I need to do so if I override the equals method. I have implemented it a fair amount of times, sometimes just calling the base method. I understand that my object should equal another instance of the object if it contains the same details (members). What is the best way to get a hash code from the class's members?

C# Solutions


Solution 1 - C#

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 instances of Frob are equal if their Foo and their Bar are equal, but FooBar doesn't matter.

Then you should define GetHashCode in terms of Foo and Bar. One way is like this:

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

Basically, you just want to incorporate all the fields that go into defining the equality. One way is to just keep accumulating and multiplying by 17 like I've done. It's fast, it's simple, it's correct, and it usually gives a good distribution.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZivkaView Question on Stackoverflow
Solution 1 - C#jasonView Answer on Stackoverflow