ToString and the Visual Studio Debugger
It is always useful to override the ToString method on each your classes. This is especially true when using the Visual Studio debugger.
This example uses the list created in this prior post.
The list is returned from a function and the breakpoint is set immediately after the return statement. Here is what the data tip looks like when hovering over the custList variable.
Notice how the items in the list show their index (0 through 3) in square braces and their class name in the curly braces. You can use the + to access the TreeView and see the property details for the class. But if you have lots of properties, you could be scrolling around to find the key bits of information you need.
You can change the information in the curly braces to contain more useful information by simply overriding the ToString method.
public override string ToString()
return this.CustomerId + " (" + this.LastName + ")";
Public Overrides Function ToString() As String
Return Me.CustomerId & " (" & Me.LastName + ")"
In this example, the most important pieces of information about the customer are the Id and last name. So that is what is returned from the ToString method. In your classes, you can return whatever information is useful for your debugging.
Now, when using the same debugging techniques described above, you can see the following when hovering over the custList variable:
NOTE: For C#, this feature is available in VS 2008 and VS 2010.
NOTE: For VB, this feature is new in VS 2010.
Now your most useful properties are displayed directly in the data tip. No need to navigate the property tree.
Override the ToString method on every business object to take advantage of this very useful debugging feature.