Overriding ToString in your classes

Posted By DeeJay Bettes on Apr 4, 2012 | 0 comments


Today I remembered a little programming gem that has really helped speed up debugging my software as well as made binding just that much more enjoyable in WPF. It’s the ability to override ToString on your class. I know, it’s really simple and you already know how to do that, but do you remember the benefits? Let me start with an example (I apologize in advance for this being in VB):

[vbnet]
Public Overrides Function ToString() As String
Return FullName
End Function
[/vbnet]

UPDATE: C# version

[csharp]
public override string ToString()
{
return FullName;
}
[/csharp]

Benefit #1: Quicker Debugging

When debugging a collection of said class (in this case ‘Person’), you can see each person’s name listed in the results section of the collection.

Instead of this:

This becomes even more useful when you are working with a more complex object (an address for example) because you can display information from several key fields and not have to dig through the object while debugging.

[vbnet]
Public Overrides Function ToString() As String
Dim addr = “”

addr += Address1

If Not String.IsNullOrEmpty(Address2) Then
If Not String.IsNullOrEmpty(addr) Then addr += “, ”
addr += Address2
End If

If Not String.IsNullOrEmpty(City) Then
If Not String.IsNullOrEmpty(addr) Then addr += “, ”
addr += City
End If

If Not String.IsNullOrEmpty(State) Then
If Not String.IsNullOrEmpty(addr) Then addr += “, ”
addr += State
End If

If Not String.IsNullOrEmpty(ZipCode) Then
If Not String.IsNullOrEmpty(addr) Then addr += ” ”
addr += FormattedZipCode
End If

Return addr
End Function
[/vbnet]

In this example you can see several fields at once for the address including the street, city, state, and zip code. This is a pretty simple example but it can be applied to increasingly more complex objects and save you a lot of time in the long-run trying to determine which object you are looking at.

Benefit #2: Free Binding

How many times have you started with a ListBox, setup the ItemsSource (WPF), and got something that looked like this:

If you setup your ToString override just right, you instantly get nice results that look more like this:

Overall, I like how just a little extra effort has really (or at least felt like) it has saved me some time and effort working with custom classes. If you found this post helpful, let me know and I might be encouraged to write down a few other programming tips.

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.