Override ToString to allow controls such as ListBox to display objects in C#

override ToString

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 displays a list of overridable methods for the class, including ToString.

See also:


Download Example   Follow me on Twitter   RSS feed




This entry was posted in classes, OOP, strings, syntax and tagged , , , , , , , , , , , , , . Bookmark the permalink.

4 Responses to Override ToString to allow controls such as ListBox to display objects in C#

  1. Pingback: Sort objects in C# |

  2. Pingback: Initialize arrays, lists, and class instances in C# |

  3. Pingback: Use auto implemented properties and initializing constructors in C#

  4. Pingback: Give classes auto implemented properties and initializing constructors in C# |

Leave a Reply

Your email address will not be published. Required fields are marked *