The following code produces the output of 46104728:
using System;
namespace TestApplication
{
internal static class Program
{
private static void Main()
{
Type type = typeof(string);
Console.WriteLine(type.GetHashCode());
Console.ReadLine();
}
}
}
But so does this:
using System;
namespace TestApplication
{
internal static class Program
{
private static void Main()
{
Type type = typeof(Program);
Console.WriteLine(type.GetHashCode());
Console.ReadLine();
}
}
}
Yet on http://ideone.com it produces varying results for each type. This issue has been reproduced on more than one system now. I’m using .NET 4.0 right now.
You’ve run into what you believe to be a problem, however, if you were to look at their hash codes in the same execution you’ll find that they’re not identical but instead rely on their order of usage:
If I run that same program again, swapping their order:
This is a non-issue at runtime as the returned values do not violate the rules for implementing
Object.GetHashCode.But, as you noted this behavior seems curious!
I delved into the source and found the implementation of
Type.GetHashCodeis foisted off ontoMemberInfo.GetHashCode, which is again foisted off ontoObject.GetHashCodewhich callsRuntimeHelpers.GetHashCode(this).It is at this point that the trail goes cold, however, my assumption is the inner workings of that method creates a new value, mapped per instance, based on the order of calls.
I tested this hypothesis by running the same code above with two instances of
Program(after adding a property to identify them):Thus, for classes which do not explicitly override
Object.GetHashCode, instances will be assigned a seemingly predictable hash value based on the order in which they callGetHashCode.Update: I went and looked at how Rotor/Shared Source CLI handles this situation, and I learned that the default implementation calculates and stores a hash code in the sync block for the object instance, thus ensuring the hash code is generated only once. The default computation for this hash code is trivial, and uses a per-thread seed (wrapping is mine):
So if the actual CLR follows this implementation it would seem any differences seen in hash code values for objects are based on the AppDomain and Managed Thread which created the instance.