简体   繁体   中英

Object with no fields: how to implement GetHashCode?

My objects in a complex structure have a property Dictionary<Object, Object> Annotations , where I can store meta and custom data used during some processing phases. I can now create a static readonly object UniqueName = new object() and use that as the key in the dictionary. I use a static readonly object because I know for sure that it is unique. No one else can ever create the exact same object instance. If instead I had used a string as a key, someone else could accidentally use the same string as the key and this could cause problems.

However, I understood from several sources (including here ) that the default GetHashCode implementation is based on the location of the object in memory. This may change when the object is moved by the garbage collector, and this would cause the hash it returns to change. When that happens, the dictionary will be unable to find the value associated with the key object.

How can I ensure that an object that has no fields never changes its hash code during its life time?

The naive solution is to create a Key object whose GetHashCode always returns 42 . However, this would severely impact the performance of the dictionary and is therefore not a solution.

implementation may change the hash it returns

The default hash code implementation will never change the value of a single object. It will never change during the lifetime of that object and can therefore safely be used. I (quickly) read those answers you're pointing at, but they don't talk about hash codes that change during the lifetime of a single object.

The default implementation of GetHashCode returns an index, rather than a memory address. This index is unique for the lifetime of the object, so even if your object is moved around in memory it will always return the same value when you call GetHashCode

However, once the object is garbage collected it valid for a new object you create afterwards to return the same value as a previous object did prior to garbage collection.

In your example the UniqueName variable will always return the same value when you call GetHashCode , and no instance of Object that you create will ever return the same hash code for the lifetime of your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM