#663 – Visual Studio Debugger Will Call Your Object’s ToString Method

When you examine the value of a variable in the Visual Studio debugger, the debugger will call the object’s ToString method in order to display a single value for the object.  If the object’s type contains other members, you can typically expand the display to show the various members.

What this means for custom types is that you’ll see the results of the default implementation of ToString, which is to just display the name of the type.  We can see this by looking at a couple of Dog objects in the Locals window of the debugger.  Note that the “value” of each is just listed as DogLibrary.Dog.

However, if we implement the Dog.ToString method and have it dump out the dog’s name and age, we’ll now see that information in the debugger.

This demonstrates why it’s often useful, for debugging purposes, to implement ToString.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #663 – Visual Studio Debugger Will Call Your Object’s ToString Method

  1. Funbit says:

    You have not mentioned the System.Diagnostics.DebuggerDisplayAttribute attribute, which has much more power! You can apply it to class, property or whatever you want and display information in desired format.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: