(turn) talk about the Equals () and GetHashCode () Methods of C #

Source: Internet
Author: User

Blog creation for more than a year, or the first time to write a blog, there is nothing wrong place also please advise.

About this write content can say is Laosheng long talk, Baidu a search a lot of. The great God can take his own detour.

Recently looking at Jeffrey Richter 's CLR Via C #, when I see the GetHashCode () method, there is one place that is not particularly clear, is to rewrite Equals () method, it is not necessary to rewrite the GetHashCode () method ( without rewriting it, but Microsoft will send a warning ). The Equals () and GetHashCode () methods need to be thoroughly understood before explaining the problem.

First, let's talk about the Equals () method:

The Equals () method, from Object, is a method that we often need to override . The default implementation of this method is probably this:

Public virtual bool Equals (object obj) {if (obj==null) return false; if (GetType ()! = obj.  GetType ()) return false; Return true;}

as you can see, the default implementation is actually compared to the memory address of two objects (== operator by default comparing memory addresses stringsystem.valuetype () ( System.ValueType () object System.ValueType () ) System.ValueType () equals () ==< The span lang= "ZH-CN" > operator is overridden by byte-by-bit comparisons. The stringstring In many places are special treatment, here will not do the drill.

Ps: According to Jeffrey Richter , when using equals () in a value type, because equals () uses reflection, it affects efficiency when compared.

After saying Equals (), come and talk about GetHashCode ().

in fact GetHashCode () is also overridden by System.ValueType () When manipulating value types . After several commonly used value types of the landlord test, the value type of GetHashCode () is basically the output of the original value ( specifically integer, Int32 except ), the authenticity to be verified. The results are as follows:

Say the value type, say the reference type, first look at the following running results:

As can be seen from the results, although string is a reference type, as long as the value is the same, the returned hashcode is the same, depending on its particularity. And we write our own type coordinates the same value but the return Hashcode is not the same, we can simply understand that is Coor1 and coor2 memory address is different, so The CLR considers them to be different.

Ps: In the lifetime of the program, the same object, the variable returned by the hashcode is the same, and is unique. However, persistent storage is never allowed, and once the program is finished and restarted, the same object cannot get the hashcode of the last time the program was run .

Learn two ways to start today's key topics.

In fact, in the above two objects (Coor1,coor2),Coor1. The return result of Equals (Coor2) is false ( because the memory address is different ), andif we want them to return to true , only the equals method can be overridden ( e.g. ).

The point is, after rewriting Equals ,vs warns , although the program ape has always ignored the warning, but this warning does need to understand, first look at the following three code.

Code snippet one or two:

Code Snippet Three:

After reading these three pieces of code, you should be able to understand why rewriting Equal is necessary to rewrite GetHashCode .

Of course, if you're not going to use Dictionary or HashTable in your code, it doesn't matter if you don't write, in other words, if you want to make a reference type Dictionary or HashTable key to use, you must override both methods.

Cause: When we put the reference type(StringExcept)Do asDictionaryOrHashTableOfKeyWhen, there may never be a basis forKeyGetValueThe value of, say, two types ofHashcodewill never be equal. Just takeDictionary, although we store it as a key-value pair,clrkey Hashcodeequalskey When the value is also keyhashcode and verify equalshashcode< The relationship between span lang= "ZH-CN" and equals (&&) gethashcodeequlas There is one method that does not rewrite, and the method that is not overridden when validating calls the default implementation of the base class, and the default implementation of both methods is based on the memory address, that is, the return value of a method will always be false

Well, you should have a re-understanding of the two ways to say so much. If still do not understand, use code to realize, categorization malleability understand.

Original sticker: http://www.cnblogs.com/xiaochen-vip8/articles/5506478.html

(turn) talk about the Equals () and GetHashCode () Methods of C #

Related Article

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.