Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, it is important if your item will be used as a key in a dictionary, or <code>HashSet&lt;T&gt;</code>, etc - since this is used (in the absence of a custom <code>IEqualityComparer&lt;T&gt;</code>) to group items into buckets. If the hash-code for two items does not match, they may <em>never</em> be considered equal (<code>Equals</code> will simply never be called).</p> <p>The <code>GetHashCode()</code> method should reflect the <code>Equals</code> logic; the rules are:</p> <ul> <li>if two things are equal (<code>Equals(...) == true</code>) then they <em>must</em> return the same value for <code>GetHashCode()</code></li> <li>if the <code>GetHashCode()</code> is equal, it is <em>not</em> necessary for them to be the same; this is a collision, and <code>Equals</code> will be called to see if it is a real equality or not.</li> </ul> <p>In this case, it looks like "<code>return FooId;</code>" is a suitable <code>GetHashCode()</code> implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that <code>new Foo(3,5)</code> has a different hash-code to <code>new Foo(5,3)</code>):</p> <pre><code>int hash = 13; hash = (hash * 7) + field1.GetHashCode(); hash = (hash * 7) + field2.GetHashCode(); ... return hash; </code></pre> <p>Oh - for convenience, you might also consider providing <code>==</code> and <code>!=</code> operators when overriding <code>Equals</code> and <code>GetHashCode</code>.</p> <hr> <p>A demonstration of what happens when you get this wrong is <a href="https://stackoverflow.com/questions/638761/c-gethashcode-override-of-object-containing-generic-array/639098#639098">here</a>.</p>
 

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