I noticed something interesting today with .net core. The Object.GetHashCode() method is not returning consistent values.The values are only consistent for the instance of the .net core process.
If the process is restarted it generates new / different hashes. This is different from .net framework which consistently produces the same hash values.
I have written a simply console application for those that don’t believe me. It can be downloaded here.
class Program { static void Main(string[] args) { List<string> stringList = new List<string>();</string></string> stringList.Add("1"); stringList.Add("2"); stringList.Add("Hello"); stringList.Add("World"); foreach(string item in stringList) { Console.WriteLine(string.Format("{0} - {1}", item, item.GetHashCode())); } Console.ReadKey(); } }
These screenshots below show the string values and their HashCodes.
To generate a consistent hash you can use SHA512.
public string ComputeHash(string value) { SHA512 sha512 = SHA512Managed.Create(); byte[] bytes = Encoding.UTF32.GetBytes(value); byte[] hash = sha512.ComputeHash(bytes); if (hash != null) { StringBuilder result = new StringBuilder(); for (int i = 0; i &lt; hash.Length; i++) { result.Append(hash[i].ToString("X2")); } return result.ToString(); } throw new InvalidOperationException("Unable to compute hash"); }
Have a loot at this: https://andrewlock.net/why-is-string-gethashcode-different-each-time-i-run-my-program-in-net-core/