Home >Backend Development >C#.Net Tutorial >How to implement C# GetHashCode
In a project, when using a hash table, you sometimes need to Override GetHashCode. Here is a common approach:
Version 1:
Implement a helper, pass type T, and return the hashcode of this type. The function logic is very straightforward, it just does 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>(T obj) { // why 31? // http://www.php.cn/ // shortly, to reduce the conflict of hashing key's distrabution return 31 * _seed + ((obj == null) ? -1 : obj.GetHashCode()); } }
Why use magic number 31? Using prime number products can relatively increase uniqueness and reduce conflicts in hash key value allocation; and 31 is for Compiler optimization considerations (effectively converts to i<<5-1). After some searching, this implementation method comes from the hash code function of string in JAVA. Here is a detailed introduction:
https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/
Implementation version 2:
can be extended This class becomes a fluent interface, which can hash various types. For value types, the significance of overloading is to reduce boxing; for collections or generics, it is to make external calls more natural and more readable.
public class HashFluent { private int _seed = 17; private int _hashContext; public HashFluent Hash<T>(T obj) { // why 31? // http://www.php.cn/ // 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 }
The above is the content of the implementation of C# GetHashCode. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!