SYSK 98: Digging Deeper Into GetHashCode

So, you think you understand when, how and why to override GetHashCode?  Then you should be able to answer the following question:  will get message box in the code below say “true” or “false”:

public class MyClass

{

    private string _param;

    public string Param

    {

        get { return _param; }

        set { _param = value; }

    }

}

. . .

MyClass c1 = new MyClass();

c1.Param = "Some string";

MyClass c2 = new MyClass();

c2.Param = "Some string";

MessageBox.Show((c1.GetHashCode() == c2.GetHashCode()).ToString());

 

The answer is “False”.

 

Why?  Because it’s not about the data the object contains – it’s about the object instance.  More over, the c1.Equals(c2) will also return False.

 

So, if I change the code to look like this:

MyClass c1 = new MyClass();

c1.Param = "Some string";

MyClass c2 = c1;

c2.Param = "Some other string";

 

what do you think the result will be?  Yes, it’ll be “True”.  More over, both c1.Param and c2.Param will now be “Some other string”.

 

That’s why if you want you custom class to return True when the data is the same, even though the object instance is different, you need to override and implement your own logic in Equals and GetHashCode methods, which is exactly what the string class does.

 

For more information on Object.GetHashCode, visit http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemObjectClassGetHashCodeTopic.asp