t.g.
t.g.

Reputation: 1749

How to switch between Debug.WriteLine() at debug and Console.WriteLine() in release mode in .NET/C#

In my C# code I would like to wrap Debug.WriteLine() and Console.WriteLine() into one function, so that it targets the debug window in debug mode and console in release mode. What is the best way to achieve it? I am new to C#. Thanks.

Upvotes: 3

Views: 1641

Answers (3)

user626528
user626528

Reputation: 14419

Always use Debug.WriteLine and add these lines to the beginning of your program:

#if !DEBUG
            var listeners = new TraceListener[] { new TextWriterTraceListener(Console.Out) };
            Debug.Listeners.AddRange(listeners);
#endif

Upvotes: 4

MgSam
MgSam

Reputation: 12803

In addition to Joel's answer, another very simple solution would be this:

private void writeLine(String s)
{

    #if DEBUG
        Debug.WriteLine(s);
    #else
        Console.WriteLine(s);
    #endif
}

This uses preprocessor directives so that it will not write to console except in Release mode. Note, it's slightly redundant as all Debug calls are removed during a Release build anyway, even without the preprocessor directive.

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 415705

Look at the System.Diagnostics.Trace class.

Trace includes a WriteLine() method similar to that on the Debug and Console classes, and supports attaching/detaching various listeners at runtime or via config file, such as the ConsoleTraceLister, DefaultTraceListner (for Debug), the TextWriterTraceListener (for files), the EventLogTraceListener, or you can create your for writing to places like database tables or syslogd aggregators.

You can just about change every current call to Debug or Console to use Trace instead, and just set the listeners you want to use. Note that the Trace methods are missing a few formatting features, but I think the configurable output source more than makes up for it.

Upvotes: 4

Related Questions