C# Debug.Write

Debug.Write is found in System.Diagnostics. It prints a message to the Visual Studio console. It is permanent—it is disabled when Debug is disabled in the program. This means we do not need to remove it to improve performance.

Debug window in Visual Studio

Example

First, this example shows the most basic usage of Debug.WriteLine. The .NET Framework has a Debug static class in System.Diagnostics. The first method here we see is WriteLine, and it may prove to be the most useful overall.

Static Class
C# program that uses Debug.WriteLine

using System.Diagnostics; // 1

static class Program
{
    static void Main()
    {
	Debug.WriteLine("Message is written"); // 2
    }
}

Output
    It will write "Message is written" to the Output window.
Program icon

In this example, we include the System.Diagnostics namespace. This is important: you have to add the using System.Diagnostics line above. This will allow you to access the Debug class directly.

It calls Debug.WriteLine. The method shows how to write a text line to the "Output" console in Visual Studio. There's picture of how this will look. We will explore some different options.

Output window

Visual Studio logo

In Visual Studio, you have an "Output" window. Go to View -> Output, and then you will see Output appear. This is where your Debug messages will be displayed. Run your program with Debug.WriteLine.

Note:You can see what the message looks like when printed at the top of this document.

Discussion

Programming tip

There are more methods in the Debug static class available. There are methods that allow you to assert on an expression or only write a message if an expression is true. One method is Debug.WriteLineIf.

Debug.WriteLineIf, WriteIfFramework: NET

Next, there is a Debug.Assert method that can be used to provide more disruptive error messages to developers. This method should be used for only the most serious errors that may occur during heavy development.

Tip:There is a separate article on the Debug.Assert method in the .NET Framework on this site.

Assert Method

Summary

We looked at the Debug.Write methods. Debug.WriteLine is the printf function from C. Permanent error handling with exceptions is always preferable in Release mode compilation. The Debug static class is for developers—not users.


C#: .NET: Debug