Debug.WriteLine() in C# - What does it do?
It will show the message/text in your output window at the bottom of Visual Studio, you can log with it some actions like "Constructor just started" then it is easier to find where error appeared. Another thing is that you can add variables to your debug output like:
Debug.WriteLine("Debug message:Shop.Add.Product({0})", Product);
Check it here: Debug.WriteLine Method
This can be used to trace or log messages in debug versions. It is only executed if your program is compiled as debug version (with the DEBUG
symbol defined).
You can create own TraceListener
s to catch the messages and log them as you need. In order to do that, you have to inherit from the abstract TraceListener
class:
public class MyListener : TraceListener
{
public override void Write(string message)
{
// log to file or db or whatever you need
}
public override void WriteLine(string message)
{
// log to file or db or whatever you need
}
}
Then you have to register an instance of your listener:
public static void Main()
{
MyListener listener = new MyListener();
Debug.Listeners.Add(listener);
// this ends up in MyListener.WriteLine, but only in a debug version
Debug.WriteLine("This is a debug log message");
Debug.Listeners.Remove(listener);
}
Further reading: How to: Create and Initialize Trace Listeners
Visual Studio always adds its own TraceListener
when debugging and outputs the messages to the output window's debug pane.