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?
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.
The toString() method returns a string as a string. The toString() method does not change the original string.
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
.
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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With