No, they will not, but look towards the end here for a more durable solution that might fit your needs.
First, there's the warning in the documentation:
Warning
A hash code is intended for efficient insertion and lookup in collections that are based on a hash table. A hash code is not a permanent value. For this reason:
- Do not serialize hash code values or store them in databases.
- Do not use the hash code as the key to retrieve an object from a keyed collection.
- Do not send hash codes across application domains or processes. In some cases, hash codes may be computed on a per-process or per-application domain basis.
...
There's more in the warning but the last one illustrates a rather good point.
Simply create a small program with this code:
Console.WriteLine("Test".GetHashCode());
Then run this for .NET Core 3.1, .NET 5 or .NET 6, repeatedly.
You'll get different values
So to answer your question, no, they will not stay the same.
However, you can roll your own implementation. Here's a rather simple implementation of a hashcode function for strings that would only change if you change it yourself:
public static int SemiStableHashCode(string input)
{
unchecked
{
byte[] bytes = Encoding.UTF8.GetBytes(input.Normalize(NormalizationForm.FormKD));
int result = 17;
foreach (byte b in bytes)
result = result * 23 + b;
return result;
}
}
Having said that, it just occurred to me that .NET 5 and 6 changed their Unicode support to use ICU instead of Win32, so who knows how "stable" my method is.