Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ToString() to show up in Debug

I'd like to get ToString() to display for a class under my control in debug mode.

It'd be nice if this was the first thing to show up when you hover over a variable with the mouse. Is there an attribute for this?

like image 791
sgtz Avatar asked Jul 26 '11 11:07

sgtz


People also ask

Can we override ToString () method in C#?

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.

What happens if you call ToString on a string?

The toString() method returns a string as a string. The toString() method does not change the original string.


3 Answers

Mark your class with

[System.Diagnostics.DebuggerDisplay("{ToString()}")]

Test:

[System.Diagnostics.DebuggerDisplay("{ToString()}")]
class MyClass
{
    private string _foo = "This is the text that will be displayed at debugging"

    public override string ToString()
    {
        return _foo;
    }
}

Now when you hover over a variable with the mouse it will show This is the text that will be displayed at debugging.

like image 172
Jalal Said Avatar answered Oct 17 '22 19:10

Jalal Said


There is DebuggerDisplayAttribute which lets you influence the display. It allows you to write fairly complex expressions to produce the debug output, although it is not recommended to do so.

However, if you have overriden ToString then the debugger is documented to display that by default. Maybe there's something wrong with the code?

like image 31
Jon Avatar answered Oct 17 '22 19:10

Jon


The output of ToString should be the default you see when debugging.

It can be overridden using the DebuggerDisplay Attribute (see MSDN).

I prefer overriding the ToString method because its easier and more versatile because it helps when writing to log files as well.

What output do you see? If you get the type name you see the default ToString.

like image 40
Zebi Avatar answered Oct 17 '22 20:10

Zebi