Search code examples
c#referenceequalsgethashcode

Gethashcode() function


Why aren't C1 and c2 have the same hashcode ? the code doesn't get to "Same".... ( i=0 in both classes)

class myclass
{
    public static int i;

    static void Main()
    {
        myclass c1 = new myclass();
        myclass c2 = new myclass();

        if (c1.GetHashCode() == c2.GetHashCode())
            Console.Write("Same");

    }
}

Solution

  • The default implementation of GetHashCode() is based on the reference, not the fields of the object.

    If you want them to be the same, you need to override GetHashCode(), so it is based on your field (and then you should remember to override Equals() also).