CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
}
}
// Are the references pointing to the same object in memory?
if (o.Equals(p1) && p2.Equals(o))
{
Console.WriteLine("Same instance!");
}
Console.ReadLine();
Here is the output of the current Main() method:
***** Fun with System.Object *****
ToString: ObjectOverrides.Person
Hash code: 46104728
Type: ObjectOverrides.Person
Same instance!
First, notice how the default implementation of ToString() returns the fully qualified name of the
current type (ObjectOverrides.Person). As you will see later during the examination of building custom
namespaces in Chapter 14, every C# project defines a “root namespace,” which has the same name of
the project itself. Here, you created a project named ObjectOverrides; thus, the Person type (as well as
the Program class) have both been placed within the ObjectOverrides namespace.
The default behavior of Equals() is to test whether two variables are pointing to the same object in
memory. Here, you create a new Person variable named p1. At this point, a new Person object is placed
on the managed heap. p2 is also of type Person. However, you are not creating a new instance, but rather
assigning this variable to reference p1. Therefore, p1 and p2 are both pointing to the same object in
memory, as is the variable o (of type object, which was thrown in for good measure). Given that p1, p2,
and o all point to the same memory location, the equality test succeeds.
Although the canned behavior of System.Object can fit the bill in a number of cases, it is quite
common for your custom types to override some of these inherited methods. To illustrate, update the
Person class to support some properties representing an individual’s first name, last name, and age, each
of which can be set by a custom constructor:
// Remember! Person extends Object.
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
246
public Person(string fName, string lName, int personAge)
{
FirstName = fName;
LastName = lName;
Age = personAge;
}
public Person(){}