If I understand correctly, in .NET the default implementation of Object.GetHashCode()
returns a value based on an object's memory address (at least for reference-types). However, the garbage collector is free to move objects around in memory. Presumably the hash code doesn't change just because the GC moves an object, so is there special handling for this interaction, or are my assumptions wrong?
GetHashCode() Method is used to return the hash code for this instance. Syntax: public override int GetHashCode (); Return Value: This method returns the hash code for the current instance.
It doesn't return a value based on the address. It returns a value based on the sync block for the object.
The sync block is allocated the first time object.GetHashCode
is called (when not overridden) or there's contention on the lock for the object. (It may be allocated if you call Wait/Pulse/PulseAll too, I haven't looked.)
The sync block is independent of the location of the object's main data in memory. Basically (as I understand it) there's one big table for sync blocks - which is kept efficient in some fashion, partly due to not every object requiring one (only ones where the system hashcode is required, or locking).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With