Debug our .NET programs using the built-in System.Diagnostics class and its Debug methods. We may need more permanent debugging logic in our code, making regular Visual Studio breakpoints less effective. We want to add lines to our source code that will flag errors to our attention.
.NET has a Debug static class available in the System.Diagnostics namespace. (As an aside, I can't express how happy I was when I found this.) The first method here I will show is called WriteLine, and it may prove to be the most useful overall (although not the most powerful). Here is example code for using WriteLine.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics; // Add this.
static class ExampleDebug
{
static public void ExampleMethod()
{
Debug.WriteLine("Message is written");
}
}
In Visual Studio, you have an "Output" window. Go to View -> Output, and then you will see the Output pane/window appear. By default, this is where your Debug messages will be printed out. Go ahead and run your program that executes the Debug.WriteLine call. What follows is an image of what the message looks like when printed.
There are methods that allow you to assert on an expression or only write a message if an expression is true. The methods are Debug.Assert() and Debug.WriteLineIf. (Additionally, there are other variants available.) Next we will look at some uses of WriteLineIf and Assert.
Catching a condition that shouldn't occur and would be a bug if it did. (This is not an exception, as it will never occur when the program is not being debugged.) These functions are compiled out of our programs when we are not debugging. Exceptions are always kept in the code. Here is an example of Assert.
{
// If value is ever -1, then a dialog will be shown when debugging is enabled.
Debug.Assert(value != -1, "Value must never be -1.");
// If you want to only write a line, use WriteLineIf.
// Debug.WriteLineIf(value == -1, "Value is -1.");
}
The Debug class is for you, the developer, and not the users. The application must always be compiled with debugging enabled. (Note that you can enable and disable DEBUG and optimization in any compilation class.)
Debug.WriteLine is the printf function from C, ported to C#. It is useful and has a place in your tool belt. However, using breakpoints in Visual Studio is easily (less typing), and more permanent error handling with exceptions is always preferable in released builds. Debug is for us developers, not the users.