[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Override a class's ToString method 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 (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.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.