Title: Override a class's ToString method to allow controls such as ListBox to display objects in C#
All classes inherit the ToString method from the Object ancestor class. Controls such as ComboBox and ListBox use the ToString methods of the objects they contain to decide what to display. By default, ToString returns a class's name, which is rarely very useful.
For instance, this example defines the following Person class.
// A simple Person class.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
When the program creates an array of these objects and displays them in a ListBox, the result is a list of their class names. If you look closely at the picture above, you'll see that every item displays the class name howto_override_tostring.Person.
Fortunately you can override the ToString method to make it display something useful. The following Person2 class does this.
// A Person class that overrides ToString.
public class Person2
{
public string FirstName { get; set; }
public string LastName { get; set; }
// Override ToString to return the Person's name.
public override string ToString()
{
return FirstName + " " + LastName;
}
}
When a ComboBox or ListBox displays this kind of object, its ToString method returns the person's first and last names. You can see the result on the right in the picture above.
Note that you don't need to type out the override's code from memory. If you type public override and a space character, IntelliSense (now renamed IntelliCode for some reason) displays a list of overridable methods for the class, including ToString.
Download the example to experiment with it and to see additional details.
|