#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: