Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The answer is mostly, it is a valid guideline, but perhaps not a valid rule. It also doesn't tell the whole story.</p> <p>The point being made is that for mutable types, you cannot base the hash code on the mutable data because two equal objects must return the same hash code and the hash code has to be valid for the lifetime of the object. If the hash code changes, you end up with an object that gets lost in a hashed collection because it no longer lives in the correct hash bin.</p> <p>For example, object A returns hash of 1. So, it goes in bin 1 of the hash table. Then you change object A such that it returns a hash of 2. When a hash table goes looking for it, it looks in bin 2 and can't find it - the object is orphaned in bin 1. This is why the hash code must not change <strike>for the lifetime of the object</strike>, and just one reason why writing GetHashCode implementations is a pain in the butt.</p> <p><strong>Update</strong><br> <a href="http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/" rel="noreferrer">Eric Lippert has posted a blog</a> that gives excellent information on <code>GetHashCode</code>. </p> <p><strong>Additional Update</strong><br> I've made a couple of changes above:</p> <ol> <li>I made a distinction between guideline and rule.</li> <li>I struck through "for the lifetime of the object".</li> </ol> <p>A guideline is just a guide, not a rule. In reality, <code>GetHashCode</code> only has to follow these guidelines when things expect the object to follow the guidelines, such as when it is being stored in a hash table. If you never intend to use your objects in hash tables (or anything else that relies on the rules of <code>GetHashCode</code>), your implementation doesn't need to follow the guidelines.</p> <p>When you see "for the lifetime of the object", you should read "for the time the object needs to co-operate with hash tables" or similar. Like most things, <code>GetHashCode</code> is about knowing when to break the rules.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload