Debugger Integration

Sometimes it is useful for an application to interact with a debugger if one is present. This is done using the System.Diagnostics.Debugger class. Properties and methods on this class allow one to detect if a debugger is attached (IsAttached) and logging messages (IsLogged); launch, attach and signal a debugger (Launch); signal an attached debugger, launching one if necessary (Break); and log messages to debugger if one is attached (Log).

Additionally, there are two custom attributes (DebuggerStepThroughAttribute and DebuggerHiddenAttribute) that can be placed on methods to control how the debugger handles the method.

DebuggerStepThroughAttribute indicates to the debugger that the method should be automatically stepped through without any user interaction. This attribute is suited for use in proxies and functions where the proxy method or thunk[5] performs some trivial and/or predictable setup, calls the real method, and then performs some similarly trivial and/or predictable teardown. When single-stepping through code that calls the proxy method or thunk, the debugger automatically steps down into the real method.

When stepping through the “real” method, the call stack in the debugger still lists the proxy method or thunk. To hide it completely, use the related DebuggerHiddenAttribute attribute. These two attributes can be combined on proxies and thunks to help the user focus on debugging the application logic, not the plumbing.

void DoWork() {...} // Real method... ...

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.