3

Why is that hash code getting generated differently every time I call the function which does the same thing({01234}). Value is a is 37121646 then when I run again it is 45592480.

    static void Main(string[] args)
    {

        int a;
        Program pp = new Program();
        a = pp.getHash();
    }

    private int getHash()
    {
        StringBuilder id = new StringBuilder();
        for (int i = 0; i < 5; i++)
        {
            id.Append(i);
        }
        return id.GetHashCode();
    }
Kar
  • 105
  • 11
  • Possible duplicate of [GetHashCode Guidelines in C#](http://stackoverflow.com/questions/462451/gethashcode-guidelines-in-c-sharp) – Steve Mar 30 '16 at 01:08

3 Answers3

6

It is because a hash code is not meant to change throughout the lifetime of an object.

The reason for this should be clear if you consider dictionaries. Dictionaries have very fast access times because objects are placed in buckets based on their hash code so when you want to get a value the dictionary doesn't need to search all of the values, it just goes straight to the bucket defined by the hash code. If the hash code changes then the look up would fail.

So, with mutable objects there's a problem. The hash code can't depend on the values, because if it did then the hash code would change when the values do, and the hash code mustn't change.

Therefore, for a StringBuilder, the hash code is based solely on the reference of the instance. If you create a new instance you have a new hash code. It's not based on the content at all.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1

I think you wanted to do this ...

  id.ToString().GetHashCode();

The Hash Code in a string is meant to be constant over a short time, but not across multiple long times or even across recompiles or versions of the runtime. i.e. do not use it beyond an execution instance. Storing the value is almost guaranteed suicide.

Sql Surfer
  • 1,344
  • 1
  • 10
  • 25
0

StringBuilder is mutable object, so using its GetHashCode method is not very practical.

As result there is no special implementation (unlike for strings) that would base result on value of the object instead of its reference identity (same for all other reference types by default).

To confirm you can check MSDN StringBuilder class for details and see that GetHashCode is "Inherited from Object."

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179