Combining hashcodes of objects

Getting a hashcode of an object in C# is not difficult. All objects has a method (defined by Object type) that can get a hashcode for the user: GetHashCode.

It has its own type of knowledge on how and where to use it, or when creating custom types, how to override this. All should be clarified on the documentation linked above.

In this post however, I want to point out that if you have two objects, how you can combine their hashcodes.

Manually

Anyone can say that this is the least difficult way. There are many tools giving a hand here, for example R# offers to generate an override GetHashCode() method for structs.

Most developers use some similar way as auto-generated methods to combine hash codes, it usually involves prime numbers, multiplication and some bitwise operation maybe an unchecked keyword.

Tuple

Tuples seem so much easier to combine hashcodes, as you 'combine' the objects first, then you get a hashcode for the tuple.

string one = "one";
string two = "two";
return Tuple.Create(one, two).GetHashCode();

It looks elegant and simple, but it has a disadvantage: it allocates an object on the heap, which can cause additional pressure on GC, as this object is about to be collected right after the hashcode is generated.

ValueTuple

Value Tuples were introduced with C# 7. This solution is also quite simple and elegant compared to the manual one too. The logic is the same as for Tuples. We combine the objects into a ValueTuple and get a hashcode. The benefit of this compared to the previous solution is that, it being fast and allocation does not happen on the heap but the stack. So this puts no extra pressure on GC, thus it is a good fit for compute intensive code paths.

string one = "one";
string two = "two";
return (one, two).GetHashCode();