tags:

views:

159

answers:

1

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?

+10  A: 

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).

Jon Skeet