Switches for Controlling the Conditional Writing of Trace Output 

You might want to make a decision about writing trace output based on the status of switches. A BooleanSwitch is a simple on-off switch, and a TraceSwitch is a switch with multiple level settings. For more information, see Trace Switches.

You can use the WriteIf and WriteLineIf methods to test a particular switch and write a message if appropriate. To use BooleanSwitch to write tracing information, use its Enabled field in an If statement or a WriteIf statement. For some examples, see Enabled in the .NET Framework reference. To use TraceSwitch to write tracing information, use TraceSwitch's Level property. For examples, see Level in the .NET Framework reference.


The following example uses the Enabled property of a BooleanSwitch called dataSwitch to determine whether or not to write a line.

Trace.WriteLineIf(dataSwitch.Enabled, "Starting connection procedure")

   "Starting connection procedure");


A TraceSwitch provides multiple setting levels, and exposes a set of properties that correspond to these levels. Thus, the Boolean properties TraceError, TraceWarning, TraceInfo, and TraceVerbose can be tested as part of a WriteIf or WriteLineIf statement. The code in this example writes the specified information only if your TraceSwitch is set to trace level Error or higher:

Trace.WriteLineIf(myTraceSwitch.TraceError, "Error 42 occurred")

   "Error 42 occurred");

When you test a TraceSwitch, the level is considered to be true if it is equal to or higher than the level you test for.

The preceding example always calls the WriteLineIf method when tracing is enabled. Therefore, the example must always execute any code necessary to evaluate the second argument for WriteLineIf. However, you will usually get better performance by testing a BooleanSwitch first and then calling the general Trace.Write method only if the test succeeds, using this code:

If MyBooleanSwitch.Enabled Then
   Trace.WriteLine("Error 42 occured")
End If

if (MyBooleanSwitch.Enabled)
   System.Diagnostics.Trace.WriteLine("Error 42 occured");

If you test the Boolean value before calling the tracing method, you avoid executing unnecessary code, because tracing always evaluates all parameters of WriteLineIf. Note that this technique would improve performance only if TraceSwitch is off during the application's normal operating mode. If TraceSwitch is on, the application must evaluate all parameters of WriteLineIf, adding time to the overall execution of the application.

See Also