C# FAQ: How can I output simple debugging messages

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How can I output simple debugging messages?

Although Visual Studio sports many useful debugging features including line-by-line stepping through source code, there are times when outputting simple text strings with variable values for debugging is more efficient.

By using the Write* methods of the System.Diagnostics.Debug class, messages can be output in a way similar to the OutputDebugString function of the Win32 API. But, the charm of the Debug class is that when building an application using the default Visual Studio Release configuration, no source code lines are generated for your Debug.Write* class. Therefore, no performance penalty is incurred by using the Debug class in release code.

To use the Debug class, follow this example:

using System.Diagnostics;
 
Debug.Write ("Debugging string");

In addition to the Write method, WriteIf, WriteLine, and WriteLineIf may be called. Here is a brief example:

bool @flag1 = true;
bool flag2  = false;
Debug.WriteLineIf (@flag1 || flag2, "Conditional debug message!");

When debugging an application with the Visual Studio debugger, all messages emitted by Write method calls show up in the Output window (View / Output menu command or Ctrl+W,O). However, when running an application outside the debugger—e.g., after starting it from Windows Explorer—, the messages can still be viewed using tools such as DebugView of Sysinternals.

Note: If the application is built using the default Release configuration, not even DebugView will display the messages; because, the Debug.Write* calls are completely eliminated. Also, code generation can be controlled by defining the DEBUG conditional directive.

Tip: The .NET debugging and tracing architecture allows redirecting debugging messages to various destinations, e.g. text files.



Personal tools