CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
be unique for all instances (such as a Social Security number), simply call GetHashCode() on that point of
field data. Thus, if the Person class defined a SSN property, we could author the following code:
// Assume we have an SSN property as so.
class Person
{
public string SSN {get; set;}
}
// Return a hash code based on a point of unique string data.
public override int GetHashCode()
{
return SSN.GetHashCode();
}
If you cannot find a single point of unique string data, but you have overridden ToString(), call
GetHashCode() on your own string representation:
// Return a hash code based on the person's ToString() value.
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
Testing Your Modified Person Class
Now that you have overridden the virtual members of Object, update Main() to test your updates.
static void Main(string[] args)
{
Console.WriteLine("***** Fun with System.Object *****\n");
// NOTE: We want these to be identical to test
// the Equals() and GetHashCode() methods.
Person p1 = new Person("Homer", "Simpson", 50);
Person p2 = new Person("Homer", "Simpson", 50);
// Get stringified version of objects.
Console.WriteLine("p1.ToString() = {0}", p1.ToString());
Console.WriteLine("p2.ToString() = {0}", p2.ToString());
// Test overridden Equals().
Console.WriteLine("p1 = p2?: {0}", p1.Equals(p2));
// Test hash codes.
Console.WriteLine("Same hash codes?: {0}", p1.GetHashCode() == p2.GetHashCode());
Console.WriteLine();
// Change age of p2 and test again.
p2.Age = 45;
Console.WriteLine("p1.ToString() = {0}", p1.ToString());
Console.WriteLine("p2.ToString() = {0}", p2.ToString());
Console.WriteLine("p1 = p2?: {0}", p1.Equals(p2));
249