3

Every object in .net has headers (SyncBlockIndex and MethodTablePointer), and when you call GetHashCode() the result could be saved in SyncBlockIndex if there is no linked SyncBlock to this object, or in SyncBlock if so.

When we don't override GetHashCode method hash code is the save during object existence, but how hash code will be storing in case we return dynamic hash code (dependent on object's state)?

I know that hash code should be the same during object existence, the purpose of question is to understand how hash code is being stored in SyncBlockIndex or in SyncBlock.

Vasyl Senko
  • 1,779
  • 20
  • 33
  • 1
    If you are writing code that has a dynamic hash code be sure to read the "[Notes to Inheritors](https://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx#Inheritors)" on the MSDN *"In general, for mutable reference types, you should override GetHashCode only if: •You can compute the hash code from fields that are not mutable; or • **You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.** "* – Scott Chamberlain Dec 02 '15 at 22:30
  • 1
    It is very heavily micro-optimized. Yes, it can store the hash code. It can also store the lock owner and recursion count when you use it in the *lock* statement. Can't do both, if you ask it to do both then it assumes the third role, a syncblock index. Never do both, that's pretty crazy. But supported. – Hans Passant Dec 02 '15 at 23:48
  • Hans, what do you mean "never do both"? And, syncblock index can store generated hash code (with not overridden method) and some more information, or can have a pointer to SyncTableEntry if there are too much information that could be stored in syncblock index (then SyncTableEntry stores hash code and more information), am I right? – Vasyl Senko Dec 06 '15 at 01:05

1 Answers1

5

how hash code will be storing in case we return dynamic hash code (dependent on object's state)?

If the hash code is dynamically computed via an override of GetHashCode is is not stored anywhere...

The usage of SyncBlockIndex as the "default" hash code for an object is an implementation detail and should not be relied upon for anything outside of the framework.

D Stanley
  • 149,601
  • 11
  • 178
  • 240