304
LESSON 25 Fine-Tuning Classes
If the list is full of Employee objects and you’ve overridden the Employee
class’s
ToString method, then a ListBox or ComboBox can display the
employees’ names.
The ListPeople example program shown in Figure 25-1 (and available as
part of this lesson’s code download) demonstrates method overriding.
When it starts, the ListPeople program uses the following code to fill its
ListBox with two Student objects and two Employee objects. Both of
these classes inherit from
Person.
private void Form1_Load(object sender, EventArgs e)
{
// Make some people.
peopleListBox.Items.Add(new Student(“Ann”, “Archer”, “101 Ash Ave”,
“Debugger”, “NV”, “72837”));
peopleListBox.Items.Add(new Student(“Bob”, “Best”, “222 Beach Blvd”,
“Debugger”, “NV”, “72837”));
peopleListBox.Items.Add(new Employee(“Cat”, “Carter”, “300 Cedar Ct”,
“Debugger”, “NV”, “72837”, “MS-1”));
peopleListBox.Items.Add(new Employee(“Dan”, “Dental”, “404 Date Dr”,
“Debugger”, “NV”, “72837”, “MS-2”));
}
The Employee class overrides its ToString method so you can see the Employees’ names in
Figure 25-1 instead of their class names. The
Student class does not override its ToString method
so Figure 25-1 shows class names for the
Student objects.
If you select a person in this program and click the Show Address button, the program executes the
following code:
// Display the selected Person’s address.
private void showAddressButton_Click(object sender, EventArgs e)
{
Person person = (Person)peopleListBox.SelectedItem;
if (person != null) MessageBox.Show(person.GetAddress());
}
This code casts the ListBox’s selected item into a Person object. The item is actually either a Student
or an
Employee but those both of those inherit from Person (they are kinds of Person) so the program
can treat them as
Persons.
If the
Person is not null, then something was selected. The program calls the object’s GetAddress
function and displays the result. If the object was actually a
Student, the result is a basic name and
address. If the object was actually an
Employee, the result is a name and address plus mailstop.
In addition to
ListBoxes and ComboBoxes, some parts of Visual Studio use an object’s ToString
method, too. For example, if you stop an executing program and hover the mouse over an object in
the debugger, a tooltip appears that displays the results of the object’s
ToString function. Similarly
if you type an object’s name in the Immediate window and press [Enter], the result is whatever is
returned by the object’s
ToString method.
FIGURE 251
596906c25.indd 304 4/7/10 12:33:58 PM