Effective C # Principle 10: Understand the flaws of GetHashCode ()

Source: Internet
Author: User

This is the only principle in this book that is occupied by an entire function, and you should avoid writing such a function. GetHashCode () is used only in one case: that is, the object is used for keywords based on the hash set, such as the classic Hashtable or dictionary container. This is good because there are a lot of problems with the GetHashCode () implemented on the base class. For reference types, it works, but is not efficient; For value types, the implementation of the base class often goes awry. This is even worse. You can write a GetHashCode () that is efficient and correct. No single function is more than GetHashCode (), and confusing. Look down and explain the confusion for you.

If you define a type and you are never going to use it for a keyword in a container, that's fine. A type like a form control, a Web page control, or a database link is not like a keyword. Under these circumstances, there is nothing to do. All reference types will get a correct hash value, even if this is inefficient. Value types should be constant (see Principle 7), in which case the default implementation is always working, even though the efficiency is bad. In most cases, you'd better avoid using GetHashCode () on an instance of a type entirely.

However, one day you create a type that you want to use as a hashtable keyword, then you need to rewrite your own GetHashCode () implementation. Continue to look, based on hashing (algorithm) of the set with hash value to optimize the lookup. Each object produces an integer hash value that is stored in the bucket based on the hash value. To find an object, you use its hash value to find the bucket (which stores the actual object). In. NET, each object has a hash value, which is determined by System.Object.GetHashCode (). Any rewrite of GetHashCode () must conform to the following three rules:

1. If two objects are equal (as defined by the operator = =), they must produce the same hash value. Otherwise, the object cannot be found in the container through the hash value.

2. For any object A, A.gethashcode () must be an instance invariant. No matter what method is invoked on a, a.gethashcode () must always return the same hash value. This ensures that objects in a bucket are always in this bucket.

3. For any input, the hash function always produces a random distribution within the integral type. This will allow you to achieve good efficiency in a hash based container.

To write a correct and efficient hash function for a type to satisfy the above three, there is a broad understanding of the type. The default version of System.Object and System.ValueType does not have any advantage. These versions must provide default behavior for your particular type, while they are not aware of these particular types. Object.GetHashCode () is the use of System.Object intrinsic members to produce hash values. Each object is created with a unique value as the Object keyword, which is stored as an integral type. These keywords start at 1 and are incremented each time any new object is generated. The ID field of the object is set in the System.Object constructor and cannot be modified in the future. Object.GetHashCode () is the return of this value as a hash value of the given object.

Note that this is the default reference type, which is not the case in other cases. )

Now we validate Object.GetHashCode () based on the three principles above. If two objects are equal, Object.GetHashCode () returns the same hash value unless you rewrite the operator = =. System.Object This version of the = = operator is the ID of the instrumented object. GetHashCode () Returns the ID field inside the object, which is good. However, if you provide your own version of = =, you must also provide your own version of GetHashCode (), thus ensuring compliance with the first rule mentioned above. Equal details see Principle 9.

The second rule has been complied with: After an object is created, its hash value cannot be changed.

The third rule, which is randomly distributed within an integer for all inputs, is not supported. This sequence of numbers is not a random distribution on the integer unless you create a large number of objects. The hash values generated by Object.GetHashCode () are mainly concentrated in the smallest possible integer range.

This means that the Object.GetHashCode () is correct, but not efficient. If you create a hash table on a reference type that you define, the default behavior inherited from the System.Object is work, but it's slow. When you create a reference type to be used for hashing keywords, you should rewrite GetHashCode () for your particular type, thus providing a better hash value that is randomly distributed across the range of integers.

Before explaining how to rewrite your own GetHashCode (), this section verifies that Valuetype.gethashcode () also adheres to the above three rules. System.ValueType overrides GetHashCode (), which provides default behavior for all value types. This version returns a hash from the first field of the type you defined. Consider this example:

public struct MyStruct
{
 private string  _msg;
 private int    _id;
 private DateTime _epoch;
}

The hash value returned from the MyStruct object is generated from the _MSG member of the object. The following code fragment always returns true:

MyStruct s = new MyStruct( );
return s.GetHashCode( ) == s._msg.GetHashCode( );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.