How to use System.HashCode.Combine with more than 8 values?

As stated in the System.HashCode documentation, adding together hashes returned by successive HashCode.Combine calls is NOT the solution. While the static HashCode.Combine method overloads only allow up to 8 values, these are just convenience methods – to combine more, instantiate the HashCode class itself and use it as follows: public override int GetHashCode() { HashCode … Read more

Why do string hash codes change for each execution in .NET?

Why do hash codes for string change for every execution in .NET In short to prevent hash collision attacks. You can roughly find out the reason from the docs of the <UseRandomizedStringHashAlgorithm> configuration element: The string lookup in a hash table is typically an O(1) operation. However, when a large number of collisions occur, the … Read more

Why might a System.String object not cache its hash code?

Obvious potential answer: because that will cost memory. There’s a cost/benefit analysis here: Cost: 4 bytes for every string (and a quick test on each call to GetHashCode). Also make the string object mutable, which would obviously mean you’d need to be careful about the implementation – unless you always compute the hash code up-front, … Read more

General advice and guidelines on how to properly override object.GetHashCode()

Table of contents When do I override object.GetHashCode? Why do I have to override object.GetHashCode()? What are those magic numbers seen in GetHashCode implementations? Things that I would like to be covered, but haven’t been yet: How to create the integer (How to “convert” an object into an int wasn’t very obvious to me anyways). … Read more

What’s the best strategy for Equals and GetHashCode?

Domain-Driven Design makes the distinction between Entities and Value Objects. This is a good distinction to observe since it guides how you implement Equals. Entities are equal if their IDs equal each other. Value Objects are equal if all their (important) constituent elements are equal to each other. In any case, the implementation of GetHashCode … Read more

tech