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)