Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does (x, y).GetHashCode() work behind the scenes?

public class Lemon{
   public int Ounces;
   public string Color;

   public override int GetHashCode() => (Ounces, Color).GetHashCode();
}

I'm curious on how that works. The (Ounces, Color) is similar to an anonymous type, but doesn't share the same syntax. And if it were an anonymous type then I'm still unsure how it'd know to get a unique hash.

A link to the relevant .net source code would be great. It's difficult to uncover since i'm unsure of what type the (Ounces, Color) ends up being compiled into.

like image 326
Bill Tarbell Avatar asked Sep 01 '26 07:09

Bill Tarbell


1 Answers

(Ounces, Color) is a tuple, which were introduced in C# 7. The corresponding type is ValueTuple<T1, T2>. From the reference source, you can tell that GetHashCode() is calculating the hash code by combining the hash codes of each object (and an additional random seed) using

 public static int Combine(int h1, int h2)
 {
     uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
     return ((int)rol5 + h1) ^ h2;
 }
like image 142
adjan Avatar answered Sep 02 '26 21:09

adjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!