You can minimize the performance penalty of instrumenting your application by using If...Then statements instead of using WriteIf statements. The following two code examples send the same debugging message. However, the first example is much faster when tracing is off, because if mySwitch.TraceError evaluates to false you do not call Write. The second example always calls WriteIf, even when mySwitch.TraceError is false and no tracing output is produced. This can result in unnecessary execution of arbitrarily complex code.

// Class-level declaration.// Create a TraceSwitch.static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application");
staticpublicvoid MyErrorMethod(Object myObject, String category) {
// Write the message if the TraceSwitch level is set to Verbose.
Trace.WriteIf(generalSwitch.TraceVerbose, myObject.ToString() +
" is not a valid object for category: ", category);
// Write a second message if the TraceSwitch level is set to Error or higher.
Trace.WriteLineIf(generalSwitch.TraceError, " Please use a different category.");
}