runtime icon indicating copy to clipboard operation
runtime copied to clipboard

string.GetHashCode() does not return the same result in version 1.1

Open LosManos opened this issue 9 years ago • 4 comments

Every time I run my program anew and call myString.GetHashCode(), it returns a new result.

Recreate

Create C# console program

    class Program
    {
        static void Main(string[] args)
        {
            var seed = "myseed";

            Console.WriteLine(seed.GetHashCode());
            Console.WriteLine(seed.GetHashCode());
        }
    }

Run the program. As expected the outputs are equal.

dotnet MyProgram.dll

555123300
555123300

Actual outcome

Now run the program again. The output is now different.

dotnet MyProgram.dll

555123300
555123300

dotnet MyProgram.dll

614890615
614890615

Expected outcome

Two runs on the same machine with the same compiled code should return the same hash for a string.
According to docs the same string should return the same hash for the same framework and the same application domain.
I have not yet checked the behaviour in dotnet core 2.

LosManos avatar May 12 '17 08:05 LosManos

According to docs the same string should return the same hash for the same framework.

Among other things those docs say:

In some cases, they can even differ by application domain.

Different runs imply different app domains.

They also say:

As a result, hash codes should never be used outside of the application domain in which they were created, they should never be used as key fields in a collection, and they should never be persisted.

mikedn avatar May 12 '17 08:05 mikedn

I updated the issue description with

or the same framework and the same application domain.

which should make it clearer.

"Different runs imply different app domains" stumbled me.
I guess is it not a bug then; possibly unclear documentation.

LosManos avatar May 12 '17 08:05 LosManos

Yes, the documentation could use some improvement. It was updated since the days .NET Framework 1.0 and now copied to .NET Core and things are getting convoluted.

mikedn avatar May 12 '17 09:05 mikedn

Feel free to close this issue.

( I filed PR # 2141 for documentation and will take it from there. )

LosManos avatar May 12 '17 09:05 LosManos