The Debugger Class
The .NET framework's Debugger class allows programs to communicate with an attached debugger. This can be the debugger built into Visual Studio or an alternative tool that supports the functionality provided by the class.
Visual Studio includes a debugger that allows you to step through the code in your program whilst monitoring the values of variables, helping you to spot potential errors. You can also use third-party debugging tools.
The .NET framework includes a special class, named Debugger, that allows you to communicate with an attached debugger using a number of static members. Although the communication is minimal, it can be effective when trying to isolate bugs. In this article we will review the Debugger class.
As the Debugger class is found in the System.Diagnostics namespace, add the following using directive to your code:
Checking if a Debugger is Attached
The Debugger class includes a property that allows you to detect if a debugger is attached. You may need to check the IsAttached property and react according its value. If a debugger is present, the property returns true. Try adding the following code to a console application in Visual Studio and launching it using F5 to debug, then Ctrl-F5 to execute without the debugger.
Console.WriteLine("Debugger not attached!");
Adding a Breakpoint
Breakpoints can be added to a project using the Visual Studio IDE. In some cases you may wish to define a breakpoint in code. You can do so using the Break method. When encountered, execution will pause and control will pass to the debugger. If no debugger is attached, you are given the option to launch one and attach it to the program.
Launching a Debugger
Sometimes you may wish to force the program to launch a debugging tool. When you execute the Launch method, a dialog box is displayed to allow selection of a debugger. The process can fail if the dialog box is dismissed. To detect success or failure, the method returns a Boolean value that is true if a debugger was launched and attached successfully.
bool launched = Debugger.Launch();
In addition to other logging and trace messages that you may generate in your code, you can log messages for the attached debugger. Logs include a numeric severity value, a category and the message. The category is limited to 256 characters in length and will be truncated if it exceeds this.
To log a message you should first check the IsLogging method's return value. If false, logging is disabled. If true, you can send a message using the Log method. The sample below logs the message, "An error occurred" in the "Errors" category with a severity level of 99. The output of the message is controlled by the debugging tool. In Visual Studio you would normally see the message in the Output window.
Debugger.Log(99, "Errors", "An error occurred");
15 December 2010