How to switch between Debug.WriteLine () to debug and Console.WriteLine () in release mode in .NET / C #
In my C # code, I would like to wrap Debug.WriteLine()
and Console.WriteLine()
in 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 #. Thank.
Take a look at the System.Diagnostics.Trace class .
Trace includes the WriteLine () method, similar to the method in the Debug and Console classes, and supports attaching / detaching various listeners at runtime or via a config file, such as ConsoleTraceLister , DefaultTraceListner (for Debug), TextWriterTraceListener (for files), EventLogTraceListener , or you can create your own entry for places like database tables or syslogd aggregators.
You can simply change each current call in Debug or Console to use Trace instead, and just set the listeners you want to use. Note that the Trace methods are missing some formatting functionality, but I think the custom output source more than makes up for that.
Always use Debug.WriteLine and add these lines to the top of your program:
#if !DEBUG
var listeners = new TraceListener[] { new TextWriterTraceListener(Console.Out) };
Debug.Listeners.AddRange(listeners);
#endif
In addition to Joel's answer, another very simple solution:
private void writeLine(String s)
{
#if DEBUG
Debug.WriteLine(s);
#else
Console.WriteLine(s);
#endif
}
It uses preprocessor directives so that it doesn't write to the console except in Release mode. Note that this is a bit redundant, as all calls Debug
are removed during Release build, even without a preprocessor directive.