How do I send out simple debug messages to help with my debugging?

Visual Studio offers tons of useful debugging features and allows you to step through your code line-by-line. However, there are times when you don’t want to step through your application, but want to make it output simple text strings with variable values, etc.

Enter the System.Diagnostics.Debug class and its Write* methods. By using the Debug class, you can output messages similarly to the way the Win32 API function OutputDebugString. However, the beauty of the Debug class is that when you build your application using the default Release configuration in Visual Studio, no code lines are generated for your Debug.Write* class. This means there’s no performance penalty for using the Debug class in release code.

To use the Debug class, simply add the “using System.Diagnostics;” statement to your C# code file, and call Debug.Write:

Debug.Write("Hello, Debugger!");

In addition to Write, you have the possibility to call WriteIf, WriteLine and WriteLineIf. For example:

When you are debugging your application under the Visual Studio debugger, all the messages that are sent out by your Write method calls end up in the Output window (View / Output menu command or Ctrl+W,O on the keyboard). However, if you are running your application outside the debugger (say, by starting it from Windows Explorer), you can still view the messages using tools like DebugView from Sysinternals.

Remember, if you build your application using the default Release configuration, even DebugView won’t show your messages because the Debug.Write* calls are eliminated altogether. You can also control code generation by defining the DEBUG conditional directive.

Tip: The .NET debugging/tracing architecture also allows you to redirect debugging messages to different destinations, such as text files. See the help topic “Trace Listeners” for more information.

The team needs your help debugging the new Visual Studio 2005 Service Pack 1 Beta . I've written about

Bhaswati

11 Oct 2010 1:57 AM

i want some debugging questions with answers immediately...its urgent plz help me.....

HAL9K

24 Jan 2011 4:00 AM

This just doesn't work, as also the Console-class doesn't output me anything in my application.

Yes, i've read about the Release-Configuration, and yes, i've read about a thousand times, that i can set the "Redirect all output text messages to the Immediate View". It just does not work.

Visual Studio 2010 is just even less usable than 2008 has ever been.

Blackpaw

19 Sep 2011 11:00 PM

Having the same problem as HAL9k in Studio 2008 on Windows 7

heipat

23 Mar 2012 1:01 AM

Just run into the same problem as Blackpaw. In my case the solution was to use an older version of DebugView and WHOA! Suddenly everything I Debug.Printed from the app showed up in DebugView. My combination that didn't work was Win7 + VS 2008 + DebugView 4.78, and the DebugView version that did work was from summer 2011.