#491 – Use Debug.WriteLine to Output Debug Information

You could use the DEBUG constant to conditionally include code in your program that outputs some debug information.  This can get unwieldy, given that you need #if/#endif directives surrounding every line that outputs some debug information.

A cleaner way to output debug information only for Debug builds is to use the Debug.WriteLine method.  (Debug is defined in the System.Diagnostics namespace).

Below is an example of a method that outputs some debug information.

        public void Bark()
            Debug.WriteLine("DEBUG INFO: Entering Dog.Bark() [{0}]", Name);

            Console.WriteLine("{0} says woof", Name);

            Debug.WriteLine("DEBUG INFO: Exiting Dog.Bark() [{0}]", Name);

To get this debugging output to go to a console window, you also need to define a listener that will direct the output of the Debug class to the console output window.

Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));

You’ll also need to include a using statement that references the System.Diagnostics namespace.

#112 – Conditionally Compiling Code in Debug Builds

By default, the C# project wizard sets up every project to have two different build configurations–Debug and Release.

Debug builds (as compared with Release builds):

  • Create executables in \bin\Debug directory
  • Do not optimize code
  • Define the DEBUG symbol
  • Write out full debug info

You build your projects in the Debug configuration during development, for the best debugging experience.  Then, when your program is ready to ship, you build the Release configuration and ship that version.

You may want to include certain code in your program that you use only for debugging purposes–so you include it in only the Debug build.  You do this using the #if directive, checking the DEBUG variable.

 static void Main(string[] args)
     DoSomeLogging();   // Only do this in Debug build
    uint x = 0x1234;
    x &= 0x0020;

Code within the #if/#endif directives will not be included in the release build.