Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Object.GetHashCode work when the GC moves an object?

Tags:

.net

hashcode

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?

like image 980
Wesley Hill Avatar asked Nov 10 '09 12:11

Wesley Hill


People also ask

What is return type of GetHashCode C#?

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.


1 Answers

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

like image 112
Jon Skeet Avatar answered Sep 21 '22 05:09

Jon Skeet