C # Implementation of GetHashCode
When using a hash table in a project, Override GetHashCode is sometimes required. Here is a common practice:
Version 1:
Implement a helper, pass type T, and return the hashcode of this type. The function logic is straightforward, but it only performs a null check. If obj is not empty, the hash code of obj is used directly.
public class HashHelper{private int _seed = 17;public int Hash
(T obj){// why 31?// https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/// shortly, to reduce the conflict of hashing key's distrabutionreturn 31 * _seed + ((obj == null) ? -1 : obj.GetHashCode());}}
Why is magic number 31 used? The product of prime numbers can be used to increase uniqueness to reduce conflicts during hash key value allocation, while 31 is for Compiler Optimization (effective conversion to I <5-1 ). I roughly searched for this implementation method from the string hash code function in JAVA. Here is a detailed introduction:
Https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/
Implementation version 2:
This class can be extended to become a smooth interface. It can hash various types. For value types, the significance of overload is to reduce the number of containers. For set or generic types, to make external calls more natural and more readable.
public class HashFluent{private int _seed = 17;private int _hashContext;public HashFluent Hash
(T obj){// why 31?// https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/// shortly, to reduce the conflict of hashing key's distrabution_hashContext = 31 * _seed + ((obj == null) ? -1 : obj.GetHashCode());return this;}public HashFluent Hash(int? value){_hashContext = 31 * _seed + ((value == null) ? -1 : value.GetHashCode());return this;}public HashFluent Hash(IEnumerable sequence){if (sequence == null){_hashContext = 31 * _hashContext + -1;}else{foreach (var element in sequence){_hashContext = 31 * _hashContext + ((element == null) ? -1 : element.GetHashCode());}}return this;}public override int GetHashCode (){return _hashContext;}// add more overridings here ..// add value types overridings to avoid boxing which is important}