CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
Console.WriteLine("Same hash codes?: {0}", p1.GetHashCode() == p2.GetHashCode());
Console.ReadLine();
}
The output can be seen here:
***** Fun with System.Object *****
p1.ToString() = [First Name: Homer; Last Name: Simpson; Age: 50]
p2.ToString() = [First Name: Homer; Last Name: Simpson; Age: 50]
p1 = p2?: True
Same hash codes?: True
p1.ToString() = [First Name: Homer; Last Name: Simpson; Age: 50]
p2.ToString() = [First Name: Homer; Last Name: Simpson; Age: 45]
p1 = p2?: False
Same hash codes?: False
The Static Members of System.Object
In addition to the instance-level members you have just examined, System.Object does define two (very
helpful) static members that also test for value-based or reference-based equality. Consider the
following code:
static void StaticMembersOfObject()
{
// Static members of System.Object.
Person p3 = new Person("Sally", "Jones", 4);
Person p4 = new Person("Sally", "Jones", 4);
Console.WriteLine("P3 and P4 have same state: {0}", object.Equals(p3, p4));
Console.WriteLine("P3 and P4 are pointing to same object: {0}",
object.ReferenceEquals(p3, p4));
}
Here, you are able to simply send in two objects (of any type) and allow the System.Object class to
determine the details automatically.
Source Code The ObjectOverrides project is located under the Chapter 6 subdirectory.
Summary
This chapter explored the role and details of inheritance and polymorphism. Over these pages you were
introduced to numerous new keywords and tokens to support each of these techniques. For example,
recall that the colon token is used to establish the parent class of a given type. Parent types are able to
define any number of virtual and/or abstract members to establish a polymorphic interface. Derived
types override such members using the override keyword.
250