2

Will the value that comes out of long.GetHashCode() be reliably the same across different .NET Framework-versions, OS-versions, processor-architecture and so on?

The question is based on other questions that mentions different results on different servers.

// Will I be the same everywhere?
var hash = 2170881568869167279.GetHashCode();

Bonus: Does the same go for int and uint?

Community
  • 1
  • 1
Seb Nilsson
  • 26,200
  • 30
  • 103
  • 130
  • 1
    You'll never get an answer here that says it is okay. That would be a very courageous answer. But yes, GetHashCode is stable for Int32, UInt32 and UInt64. They are very simple, no need to ever tinker with them like String.GetHashCode(). – Hans Passant Jan 11 '13 at 12:32
  • @HansPassant Thanks for the comment. Add a real answer with a link and I'd vote for it. We'll see which I find to be the correct after a while. – Seb Nilsson Jan 11 '13 at 12:34
  • @HansPassant: But at least for `UInt64`, it can't be used to define identity, because `GetHashCode` always returns an `int`. So there will be collisions. – Daniel Hilgarth Jan 23 '13 at 15:37

1 Answers1

5

Per the contract of GetHashCode, it is not even required to be the same on the same machine in two different processes:

the default implementation of this method must not be used as a unique object identifier for hashing purposes.

For certain types it could be - and probably is - implemented in a way that will always return the same hash code, even on different machines. But that is an implementation detail you should not rely on - it could change without notice.

Furthermore, two different objects can legally have the same hash code. In your example with long, on average you will have each hashcode long.MaxValue / int.MaxValue times when you create the hashcode for all values from long.MinValue to long.Maxvalue.

Conclusion:
No, it is not a reliable way to identify an instance of an object.

When dealing with numbers, you could simply use the number itself or use a real hashing algorithm.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • +1. "it could change without notice." And did, as I recall, between two different .NET versions. At least once. – Jim Mischel Jan 11 '13 at 12:18