DebuggerDisplay Can Do More

Illustration

Quite often I see code that overrides ToString() just for the sake of a tooltip when debugging. Don’t misunderstand me, I like a good tooltip but, if that is single reason for override, there is other way to do it.

.NET has [DebuggerDisplay](http://msdn.microsoft.com/en-us/library/x810d419.aspx) attribute. Simple class could implement it like this:

[DebuggerDisplay("Text={Text} Value={Value}")]
internal class XXX {
    public string Text { get; private set; }
    public float Value { get; private set; }
}

And that will result in debugging tooltip Text="MyExample" Value=3.34. Not too shabby. But what if we want our display without quotes and with different rounding rules?

There comes in expression parsing part of that attribute. Anything withing curly braces ({}) will be evaluated. So let’s change our example to:

[DebuggerDisplay(@"{Text + "" at "" + Value.ToString(""0.0"")}")]
internal class XXX {
    public string Text { get; private set; }
    public float Value { get; private set; }
}

This expression will result in tooltip that shows MyExample at 3.3. And I see that as an improvement.

Nice thing never comes without consequences. In this case advanced formatting is dependent on language used. If you stick to single language you will not see anything wrong. However, if you mix and match (e.g. C# and VB) you might end up in situation where DebuggerDisplay expression is evaluated by language currently being debugged regardless of language which it was written in.

I usually ignore that risk for sake of convenience.

P.S. And anyhow worst thing that could happen is not seeing your tooltip in very rare situations. Your actual program will not be affected in any manner.