is hashcodecombine commutative?

Why not carry out a simple experiment, e.g.

public static void Experiment() {
  for (int i = 0; i < 100; ++i)
    for (int j = 0; j < 100; ++j) {
      int a = HashCode.Combine(i, j);
      int b = HashCode.Combine(j, i);

      if (a != b) {
        Console.Write($"Combine({i}, {j}) = {a} != {b} = Combine({j}, {i})");

        return; 
      }
  }

  Console.Write("Seems to be commutative");  
}

Outcome:

Combine(0, 1) = -839320321 != 864340100 = Combine(1, 0)

So Hash.Combine (current implementation, .Net Core 3.1) is not commutative

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top