WriteIf and WriteLineIf

I came across this about two years ago when I was putting together a presentation on debugging in .Net.  It came up again last week, so I thought I would share on here.

If the WriteLineIf and WriteIf methods of the Trace and Debug classes are provided a method for the value or category parameter, it is executed even if the condition is false.  For example, the following code will produce a console with the text “GetErrorMessage is run“ printed three times, even though the condition for the WriteLineIf statement is 1==0, which is false.

using System;

namespace TestWriteLine
{
 class Class1
 {
  ///
  /// The main entry point for the application.
  ///
  [STAThread]
  static void Main(string[] args)
  {
   System.Diagnostics.Debug.WriteLineIf(1==0, GetErrorMessage(), GetErrorMessage());
   System.Diagnostics.Trace.WriteLineIf(1==0, GetErrorMessage());
   Console.ReadLine();
  }

  static string GetErrorMessage()
  {
   Console.WriteLine(“GetErrorMessage is run”);
   return “Test Error Message”;
  }
 }
}

While this isn’t a big deal, and probably normally isn’t even come across, it’s something to take note of.  If, for instance, you were writing information out in the Trace for debugging purposes and want to get specific information about the Process, Thread, Security Context, etc. built up in a string and then written out (say in the GetErrorMessage method above), that code would execute even if the conditional on the WriteLineIf statement was false.

Just not the behavior I would have expected.