The MSDN article here states, that the default implementation of GetHashCode() does not guarantee unique results and should be not used as an identifier. So my question is whether DateTime.Now has its own implementation that would give out unique hashes. Thx for help
The MSDN article here states, that the default implementation of GetHashCode() does not guarantee
Share
First, it would be a mistake to rely on the particular implementation of
GetHashCodeforDateTime. That is something that is hidden from you. Relying on hidden details is a bad code smell; they could change on you at any moment and break your code.Second, it turns out that
DateTimeinternally stores a 64-bit integerDateTime.Ticksthat measures the number of 100-nanosecond units since the epoch (midnight on January 1, 0001). Therefore,DateTimeinstances require at least 64-bits of information. But hash codes are 32-bit integers and therefore hash codes can not be unique (you can not map 64-bit space to 32-bit space without collisions).To be explicit, you can see the source code for
DateTime.GetHashCode:As you can see, it does some “folding” to squeeze
InternalTicksinto a 32-bit integer.In general, do not rely on hash codes being unique. The input space is generally larger than the space being hashed to (the space of all 32-bit integers).
If you absolutely must have a unique key to represent a
DateTimeobject, useDateTime.ToBinary. This will provide you with a 64-bit integer that is unique and can be used to reconstitute theDateTime(useDateTime.FromBinary).