Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetHashCode for StringBuilder generating different code

Tags:

c#

.net

hashcode

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();
    }
like image 583
Kar Avatar asked Sep 06 '25 03:09

Kar


2 Answers

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.

like image 147
Enigmativity Avatar answered Sep 07 '25 23:09

Enigmativity


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."

like image 26
Alexei Levenkov Avatar answered Sep 07 '25 22:09

Alexei Levenkov