Home » c# » C# debugging: [DebuggerDisplay] or ToString()?

C# debugging: [DebuggerDisplay] or ToString()?

Posted by: admin November 30, 2017 Leave a comment

Questions:

There are two ways to increase the usefulness of debugging information instead of seeing {MyNamespace.MyProject.MyClass} in the debugger.

These are the use of the DebuggerDisplayAttribute and the ToString() method.

using System.Diagnostics;
...

[DebuggerDisplay("Name = {Name}")]
public class Person
{
    public string Name;
}

or

public class Person
{
    public string Name;
    public override string ToString()
    {
        return string.Format("Name = {0}", Name);
    }
}

Is there any reason to prefer one to the other? Any reason not to do both? Is it purely personal preference?

Answers:

Using [DebuggerDisplay] is meant only for the debugger. Overriding ToString() has the “side effect” of changing the display at runtime.

This may or may not be a good thing.

Often, you want more info during debugging than your standard ToString() output, in which case you’d use both.

For example, in your case, the “ToString” implementation seems odd to me. I would expect a “Person” class ToString() implementation to just return the Name directly, not “Name = PersonsName”. However, during debugging, I might want that extra information.

Questions:
Answers:

“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.” – MSDN

If what ToString() returns and you see in debugger is not what you would like then you use DebuggerDisplayAttribute.