Search code examples
c#hashtypesgethashcode

GetHashCode of System.Type returns different values


Why does GetHashCode returns different values for the same type. If i execute this code:

Console.WriteLine(typeof(Guid).GetHashCode());

In different applications, i get different hash codes.

If i execute the following statement multiple times in different applications:

Console.WriteLine("ABC".GetHashCode());

I get always the same hash code. But why is the hash code changing for System.Type, but not for System.String?

Thank you.


Solution

  • Neither System.String nor System.Type guarantees persistable hashcodes as a part of its contract. The fact that it so happens to work with System.String in your particular case is an implementation detail that cannot be relied upon. If you need to persist or export a hash of a string, use a different string hashing method. Persisting or exporting information about a type should probably use information like FullName, AssemblyQualifiedName, and others, depending on the exact requirement.