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

[亡魂溺海] 提交于 2019-12-02 17:22:23

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.

Piotr Perak

"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.

Slowness of the debugger can also be taken into account:

DebuggerDisplayAttribute format expression is interpreted by the debugger after each debugging step / breakpoint.

ToString is compiled in your code and is therefore much faster to execute by the debugger.

That's the same with conditional breakpoints: If the conditional expression is too slow to interpret by the debugger each time the execution reach the breakpoint, it can be useful to remove the breakpoint and instead add temporary code like this: if (condition) Debugger.Break();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!