Alternatively, you can count it as the sum of the hashes of its fields:
public override int GetHashCode() { int result; uncheked { // если поле ссылочного типа, // то необходима проверка на null // если field1 будет null, то подставится 0 result = this.field1?.GetHashCode() ?? 0; result += this.field2?.GetHashCode() ?? 0; //... result += this.fieldN.GetHashCode(); } return result; }
Or through the creation of an anonymous class ( peeped in English SO ):
public override int GetHashCode() { return new { this.field1, this.field2, /*... ,*/ this.fieldN }.GetHashCode(); }
This option also works fairly quickly, but with the exception that each call generates an anonymous class.
There you can see the answer of John Skit . He set up an algorithm with the choice of two random constants (they do not change, random - because you need to come up with them once) and calculate the hash as follows:
public override int GetHashCode() { unchecked { int hash = 17; // если поле ссылочного типа, // то необходима проверка на null hash = hash * 23 + field1?.GetHashCode() ?? 0; // если это, например, int, то проверка ни к чему hash = hash * 23 + field3.GetHashCode(); return hash; } }
I added a check for null from myself, about which he writes there in the answer
I advise you to follow the link and see that there are many useful things written there.
GetHashCode(){return GetRuStackOverflow();}. - user207618HashCodesite, which becameRuStackOverflow. The irony :) - user207618