CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
Overriding System.Object.ToString()
Many classes (and structures) that you create can benefit from overriding ToString() in order to return a
string textual representation of the type’s current state. This can be quite helpful for purposes of
debugging (among other reasons). How you choose to construct this string is a matter of personal
choice; however, a recommended approach is to separate each name/value pair with semicolons and
wrap the entire string within square brackets (many types in the .NET base class libraries follow this
approach). Consider the following overridden ToString() for your Person class:
public override string ToString()
{
string myState;
myState = string.Format("[First Name: {0}; Last Name: {1}; Age: {2}]",
FirstName, LastName, Age);
return myState;
}
This implementation of ToString() is quite straightforward, given that the Person class only has
three pieces of state data. However, always remember that a proper ToString() override should also
account for any data defined up the chain of inheritance.
When you override ToString() for a class extending a custom base class, the first order of business is
to obtain the ToString() value from your parent using the base keyword. After you have obtained your
parent’s string data, you can append the derived class’s custom information.
Overriding System.Object.Equals()
Let’s also override the behavior of Object.Equals() to work with value-based semantics. Recall that by
default, Equals() returns true only if the two objects being compared reference the same object instance
in memory. For the Person class, it may be helpful to implement Equals() to return true if the two
variables being compared contain the same state values (e.g., first name, last name, and age).
First of all, notice that the incoming argument of the Equals() method is a general System. Object.
Given this, your first order of business is to ensure the caller has indeed passed in a Person object, and as
an extra safeguard, to make sure the incoming parameter is not a null reference.
After you have established the caller has passed you an allocated Person, one approach to
implement Equals() is to perform a field-by-field comparison against the data of the incoming object to
the data of the current object:
public override bool Equals(object obj)
{
if (obj is Person && obj != null)
{
Person temp;
temp = (Person)obj;
if (temp.FirstName == this.FirstName
&& temp.LastName == this.LastName
&& temp.Age == this.Age)
{
return true;
}
else
{
return false;
247