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
to the much simpler
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.
Comments
blog comments powered by Disqus