Some thoughts on Object.GetHashCode()

One of the architects on the CLR
team just reminded me of a detail about GetHashCode on object… Specifically you
should NOT use it as a unique
ID for an object. It is possible
for two different objects to return the same value. "urn:schemas-microsoft-com:office:office" />


By the contract of GetHashCode we
know that if two objects have different hash codes, they are not the same
object. But if two objects have the
same hash code, they are not necessarily the same object (but it’s very likely
that they are).

Today we use the index of the sync
block for the hashcode. This has
some perf issues as we delay create the sync block so it is allocated only when
needed. With V1.0 ands V1.1 this
means calling GetHashCode creates a syncblock. In a future version we will change
GetHashCode to return essentially a random number. The number is of course stable so
that invoking Object.GetHashCode repeatedly on any given object will always
return the same value. But it does
make the contract described above more apparent, so you are well advised to code
with that that in mind today.