Bug with Debug.WriteLine(string format, params object[] args) in Visual C# 2010 Express


I have noticed something odd with the behavior of the Debug.Writeline() method (from System.Diagnostics).

Two of the 5 overloaded versions of the method are:

Debug.WriteLine(string format, params object[] args) Debug.WriteLine(string message, string category)

Whenever I try to use version 1, if I only have a single format object in the format string, and the only param is a string, it appears to be interpreted as version 2.  If I have two or more format objects in the format string, it works as

For example, assuming string t1 = “moo”

Debug.WriteLine(“test {0}”, s1); will yield: “moo: test{0}” in the output window, but

Debug.WriteLine(“test {0} {1}”, s1, s1); will yield “test moo moo” in the output window.

Surely, there has to be something better than Debug.WriteLine(“test {0}”, (System.Object)s1); to affect the desired result if s1 is a string.

Wow! This is a new gotcha for .NET 4.0.  It is not a regression as the ability to use format  strings did not exist for Debug.WriteLine in previous versions.Unfortunate, C# overload resolution rules require that the (string, string) overload be used in this case.  It is a “tighter” match for the argument types.While this convenience method is nice, I’m kind of surprised that Microsoft added that overload with the params  keyword at all given this (IMHO) serious gotcha…Workarounds:Debug.WriteLine(“Hello {0}”, newobject[] { “World” });

There is a better workaround: since the latest overload of Debug.WriteLine is an exact copy of Debug.Print, you can just use:Debug.Print (“Hello {0}”, “World”);And since Debug.Print doesn’t have a conflicting overload, it will not produce the unexpected behavior you witnessed.HTH

> Debug.Print (“Hello {0}”, “World”);Right, good catch, thanks for noticing!