Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Wow, that's actually several questions in one :-). So one after the other:</p> <blockquote> <p>it's been cited that the value of GetHashCode should never change over the lifetime of the object. How does that work if the fields that it's based on are mutable? </p> </blockquote> <p>This common advice is meant for the case where you want to use your object as a key in a HashTable/dictionary etc. . HashTables usually require the hash not to change, because they use it to decide how to store &amp; retrieve the key. If the hash changes, the HashTable will probably no longer find your object. </p> <p>To cite the docs of Java's <em>Map</em> interface:</p> <p><em>Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.</em></p> <p>In general it's a bad idea to use <em>any</em> kind of mutable object as a key in a hash table: It's not even clear what should happen if a key changes after it's been added to the hash table. Should the hash table return the stored object via the old key, or via the new key, or via both? </p> <p>So the real advice is: Only use immutable objects as keys, and make sure their hashcode never changes either (which is usually automatic if the object is immutable).</p> <blockquote> <p>Also what if I do want dictionary lookups etc to be based on reference equality not my overridden Equals?</p> </blockquote> <p>Well, find a dictionary implementation that works like that. But the standard library dictionaries use the hashcode&amp;Equals, and there's no way to change that.</p> <blockquote> <p>I'm primarily overriding Equals for the ease of unit testing my serialization code which I assume serializing and deserializing (to XML in my case) kills the reference equality so I want to make sure at least it's correct by value equality. Is this bad practice to override Equals in this case?</p> </blockquote> <p>No, I'd find that perfectly acceptable. However, you should not use such objects as keys in a dictionary/hashtable, as they're mutable. See above.</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