Here’s an odd warning that came up when I was working on last weeks Code Gardening post:

Warning CA1307
The behavior of ‘string.GetHashCode()’ could vary based on the current user’s locale settings. Replace this call in ‘ModifyVocabularyWordScreen.GetHashCode()’ with a call to ‘string.GetHashCode(System.StringComparison)’.

This warning comes up because it’s a good idea to prefer locale-aware versions of methods where they are available.

But.

The values returned by .GetHashCode() should never be used outside of the current process. Differences between different users, with different cultural settings, would therefore be irrelevant. Also, it’s entirely possible for updates to the .Net runtime to change the results of .GetHashCode(), so it’s important to treat them as ephemeral values, making this warning a little odd.

Instead of making the suggested change, I opted to use the new struct HashCode to combine hash code values in a more robust way.

In VocabularyWord, the code changes from

public override int GetHashCode()
{
    unchecked
    {
        int hash = 17;
        hash = (hash * 23) + Spelling.GetHashCode();
        hash = (hash * 23) + Phrase.GetHashCode();
        hash = (hash * 23) + Pronunciation.GetHashCode();
        return hash;
    }
}

to the much simpler

public override int GetHashCode()
    => HashCode.Combine(Spelling, Phrase, Pronunciation);

Thus nicely bypassing the locale warning. :-)

In fact, documentation for .NET Core says:

It is best-practice to consider hash codes as an implementation detail, as the implementation may change across assembly versions. Do not store hash codes produced by HashCode in serialized structures, for example, on-disk.HashCode uses a statically initialized random seed to enforce this best practice, meaning that the hash codes are only deterministic within the scope of an operating system process.

Also, it’s entirely possible for updates to the .Net runtime to change the results of .GetHashCode(), so it’s important to treat them as ephemeral values.

Prior post in this series:
Code Gardening
Next post in this series:
Modifying Words, Part the First

Comments

blog comments powered by Disqus