When defining custom types in .NET, if necessary, not only should you rewrite the EQUALS method, but also rewrite the GethashCode method, which is very important. This is particularly important when the type is used as a key in a collection of dictionaries and hash sets.
Why rewritten Gethashcode?Gethashcode is responsible for generating hash code for objects. Without custom comparators, collecting this hash code to determine the proper schedule of finding objects in it. If the hash code of the two objects is the same, it is assumed that they are located in the same bucket, and only at that time, Equals will be called to perform more detailed equal checks.
The preferred Gethashcode method
Considering the provided FOO class, the rewriting of Equals is compared based on the FOOID attribute. The first choice of Gethashcode is returned to FOOID. This method is consistent with Equals logic to ensure that objects with the same FOOID have the same hash code.
The consequences of incorrect rewriting Gethashcode
ignore the rewriting Gethashcode and use the default implementation, which will cause the following adverse effects:
Miss equal object: If the two objects are actually equal but have different hash codes, they may never be considered equal because they will not call Equals.
Too many conflicts:Incorrect Gethashcode implementation will lead to excessive conflicts, and many of them are allocated with the same hash code, which leads to low performance efficiency.
Convenient transportation: Considering providing the load == and! = The operator to facilitate comparison.
The above is the detailed content of Should You Override GetHashCode When Overriding Equals in .NET?. For more information, please follow other related articles on the PHP Chinese website!