views:

58

answers:

1

Hey all,

There are two ways I know of to increase the usefulness of debugging information so you don't see {MyNamespace.MyProject.MyClass} in the debugger. These are the use of the DebuggerDisplay attribute and the ToString method.

[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?

+6  A: 

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.

Reed Copsey
+1 To add on to Reed's "side effect" point: `ToString` is often used as a "default display string," e.g., by `Console.WriteLine` or WPF data binding.
Stephen Cleary
Sure; the string's format was just given for a visual example to emphasize its similarity to the string given for DebuggerDisplay. The DebuggerDisplay format could as well return the name directly, as you say. I see your point about side effects though--it's the kind of distinction I'm looking for. I don't typically utilize the ToString method on classes much (except for the purpose I've given above) so its other usages weren't as apparent to me. Thanks!
bwerks