Home » c# » Debug.Print vs. Debug.WriteLine

Debug.Print vs. Debug.WriteLine

Posted by: admin February 22, 2018 Leave a comment

Questions:

What’s the difference between Debug.Print and Debug.WriteLine? The summary of both in MSDN is the same:

Writes a message followed by a line terminator to the trace listeners in the Listeners collection.

Debug.WriteLine has more overloads. I can’t see a reason why Debug.Print would be used instead of Debug.WriteLine?

Answers:

They both do the same thing, but its interesting that Debug.Print will only take a string, while Debug.WriteLine will accept an object which ends up calling the object’s ToString method.

With Reflector:

[Conditional("DEBUG")]
public static void Print(string message){
    TraceInternal.WriteLine(message);
}

[Conditional("DEBUG")]
public static void WriteLine(string message){
    TraceInternal.WriteLine(message);
}

[Conditional("DEBUG")]
public static void WriteLine(object value)
{
    TraceInternal.WriteLine(value);
}

I’d be willing to bet that Debug.Print was a hold over from Visual Basic.

Edit: From a tutorial on Tracing VB.NET Windows Application:

In Visual Basic.NET 2005, the
Debug.Write, Debug.WriteIf,
Debug.WriteLine, and Debug.WriteLineIf
methods have been replaced with the
Debug.Print method that was available
in earlier versions of Visual Basic.

Sure sounds like Debug.Print was a hold over from pre-C# days.

Questions:
Answers:

Debug.Print and Debug.WriteLine each offers an overload that takes a single string parameter. Internally, those single-parameter methods work in the same way and call this method:

TraceInternal.WriteLine(message);

The difference between the two methods is that Debug.Print offers an overload with two arguments: Debug.Print(String, Object[]). That overload of Print can display a formatted string. There is no overload of Debug.WriteLine that offers that functionality, but you can of course use:

Debug.WriteLine(string.Format())

WriteLine was introduced in .NET Framework 1.1 and Print in Framework 2.0. In my opinion, Microsoft should have stayed with WriteLine as the name of the method and added a WriteLine(String, Object[]) overload, instead of adding the Print method.

Questions:
Answers:

They didn’t want to risk breaking a .NET language that considers both overloads ambiguous. They very nearly are, WriteLine(“foo”) could match WriteLine(string) and WriteLine(string, params object[]). C# has a rule for it but that’s specific to that language.

Questions:
Answers:

From the prototypes:

public static void Print(string message);
public static void Print(string format, params object[] args);

public static void WriteLine(object value);
public static void WriteLine(string message);

It looks like Print can do formatted strings and WriteLine can dump objects.