Quantcast
Channel: User Tarmil - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by Tarmil for How do you override `GetHashCode()` idiomatically for an algebraic data type?

$
0
0

The recommended way to combine hash codes since .NET Standard 2.1 is using System.HashCode.Combine(). To differentiate between cases, you can add an integer argument.

override this.GetHashCode() =    match this with    | Ctor0 n -> HashCode.Combine(0, n)    | Ctor1 (a, b) -> HashCode.Combine(1, a, b)    | Ctor2 (a, b) -> HashCode.Combine(2, a, b)    | Ctor3 xs -> HashCode.Combine(3, myCustomHash xs)

I added the integer argument in all cases for consistency, but I think you're right that Ctor0 and Ctor3 don't really need it.

If you need to be compatible with older .NET versions, you can rely on hash for tuples instead. (I'm using struct tuples here which should allocate less than normal tuples)

override this.GetHashCode() =    match this with    | Ctor0 n -> hash struct(0, n)    | Ctor1 (a, b) -> hash struct(1, a, b)    | Ctor2 (a, b) -> hash struct(2, a, b)    | Ctor3 xs -> hash struct(3, myCustomHash xs)

Viewing all articles
Browse latest Browse all 38

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>