I am looking for a good concrete example where it is clearly desirable to override ToString()
with something, but to use a [DebuggerDisplay(...)]
custom attribute to display something else in the debugger?
views:
87answers:
4Suppose you have an existing application where .ToString() is expected to, say, serialize the object to a string. Not that it's a good idea, but suppose you're in that situation. You could then still use [DebuggerDisplay(...)] to make your life easier, without modifying this (admittedly bad, but I suspect not unusual) contract between the class and the rest of the application.
Say, for example, a Node object for a binary tree.
The ToString()
would merely want to display the payload for that node, while the DebuggerDisplay
would probably also show which nodes it was pointing to.
You can add also note that ToString() is not evaluated by the debugger in VB.NET. So if you plan on developing with several languages, getting used to this attributes in a good idea.
I prefer to use this attribute over the ToString because suppose I don't need to use the ToString() method for anything else, I don't like the idea of having a method sitting there for nothing.
And if you need another reason, I think it makes more sense to use a declarative approach because the debugger display string is just some metadata, it could also be used by some other tools.
Lazy in .NET4 uses it to display important properties in debug:
[Serializable,
DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}"),
DebuggerTypeProxy(typeof(System_LazyDebugView<>)), ComVisible(false), HostProtection(SecurityAction.LinkDemand, Synchronization=true, ExternalThreading=true)]
public class Lazy<T>
{
...
}
ArrayList also use:
[Serializable, ComVisible(true), DebuggerTypeProxy(typeof(ArrayListDebugView)),
DebuggerDisplay("Count = {Count}")]
public class ArrayList : IList, ICollection, IEnumerable, ICloneable
{
...
}
Or Color structure:
[Serializable, StructLayout(LayoutKind.Sequential), TypeConverter(typeof(ColorConverter)),
DebuggerDisplay("{NameAndARGBValue}"),
Editor("System.Drawing.Design.ColorEditor, System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public struct Color
{
...
}
You can see it by using .NET Reflector tool.