views:

33

answers:

2

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");

    }
}
+1  A: 

Because you're creating different instances of the same class. Each instance of a class has its own hashcode, and the hashcode is used to identify an object in your program's memory, even if they both share the same field values.

If you did this, however, it'll write "Same", because you're just creating two variables that point to the same object (i.e. you're passing the reference of c1 to the object to c2):

    myclass c1 = new myclass();
    myclass c2 = c1;

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

Of course, I don't think this is what you're looking to achieve.

BoltClock
+1  A: 

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 overload Equals() also).

driis