There is no guarantee, because you can go and implement the class using the GetHashCode method, which does arbitrary stupid things. The compiler will not stop you from doing this.
Another question: can you expect GetHashCode always return the same value. The answer to this question is yes, basically. This is a design decision. However, for most classes, the ability to use instances as a key in a dictionary is important for implementing GetHashCode so that the value never changes, for example, without overlapping it, or only redefining it to save reflection costs.
Remarkably, this includes StringBuilder , so the race condition marked by dasblinkenlight does not really exist: unlike String , StringBuilder will always return the same hash code.
So why basically? The answer to this is a bit uncomfortable. Technically, the String class is not immutable. There are some evil (i.e., unsafe) ways to change the contents of a string without changing the link, which in turn will lead to different hash codes for the same link. You will also find a number of people implementing values like Equals and GetHashCode for classes that suffer from the same problem (and you don't need to use unsafe code to get into the problem).
Thus, there is no guarantee, but this is a fair assumption. Just document this assumption so that users of your code do not run into difficulties, and everything should be in order.
Georg
source share