1

How do I ensure two different instances of a class have the same hash code? So when one of them is in a HashSet, the Contains function returns true.

Here is my code:

public class Position
 {
     public int row, col;
     public override bool Equals(object obj)
     {
         return ((Position)obj).row == row && ((Position)obj).col == col;
     }
 }

And here is how I use it:

HashSet<Position> hash = new HashSet<Position>();
Position position = new Position(3, 1);
Position position2 = new Position(3, 1);
hash.Add(position);
Console.WriteLine(hash.Contains(position2));
jeroenh
  • 26,362
  • 10
  • 73
  • 104
MisterBirs
  • 81
  • 5
  • 3
    Hi Shlomi, and welcome to stack overflow. You should implement GetHashCode, refer to the question I marked as duplicate. See also [the documentation](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type) and [this guidance from Eric Lippert](https://blogs.msdn.microsoft.com/ericlippert/2011/02/28/guidelines-and-rules-for-gethashcode/) – jeroenh Aug 24 '18 at 08:23

1 Answers1

-2
using System;
using System.Text;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        HashSet<Position> hash = new HashSet<Position>();
        Position position = new Position(3, 1);
        Position position2 = new Position(3, 1);
        hash.Add(position);
        Console.WriteLine(hash.Contains(position2));
    }
}


public class Position
 {
     public int row, col;

     public Position(int row, int col) {
       this.row =  row;
        this.col =  col;
     }

     public override bool Equals(object obj)
     {
         return ((Position)obj).row == row && ((Position)obj).col == col;
     }

     public override int GetHashCode()
     {
        Console.WriteLine((row + col) * (row - col + 1));
        return (row + col) * (row - col + 1);
     }
 }
  • So `13, 4` and `1, 34` have the same hash code. Not the end of the world but not pretty. But two instances of `123456, 123456` are going to get different hash codes and so this doesn't provide an answer to the question the OP asked. – Damien_The_Unbeliever Aug 24 '18 at 08:40