A switch provides an efficient mechanism for controlling tracing and debugging output at run time using external settings. The Switch class implements default behavior for switches, allowing you to change the switch level at run time.
This class is the base class for the BooleanSwitch, SourceSwitch and the TraceSwitch classes. These switches meet most debugging and tracing needs. For more information about trace switches, see Trace Switches.
You must enable tracing or debugging to use a switch. The following syntax is compiler specific. If you use compilers other than C# or Visual Basic, refer to the documentation for your compiler.
To enable debugging in C#, add the /d:DEBUG flag to the compiler command line when you compile your code, or you can add #define DEBUG to the top of your file. In Visual Basic, add the /d:DEBUG=True flag to the compiler command line.
To enable tracing using in C#, add the /d:TRACE flag to the compiler command line when you compile your code, or add #define TRACE to the top of your file. In Visual Basic, add the /d:TRACE=True flag to the compiler command line.
To set the level of your switch, edit the configuration file that corresponds to the name of your application. Within this file, you can add a switch and set its value, remove a switch, or clear all the switches previously set by the application. The configuration file should be formatted like the following example:
<configuration>
<system.diagnostics>
<switches>
<add name="mySwitch" value="true" />
</switches>
</system.diagnostics>
</configuration>
This example configuration section defines a BooleanSwitch with the DisplayName property set to mySwitch and the Enabled value set to true. Within your application, you can use the configured switch value by creating a BooleanSwitch with the same name, as shown in the following code example.
Private Shared boolSwitch As New BooleanSwitch("mySwitch", _
"Switch in config file")
Public Shared Sub Main(ByVal CmdArgs() As String)
'...
Console.WriteLine("Boolean switch {0} configured as {1}", _
boolSwitch.DisplayName, boolSwitch.Enabled.ToString())
If boolSwitch.Enabled Then
'...
End If
End Sub
private static BooleanSwitch boolSwitch = new BooleanSwitch("mySwitch",
"Switch in config file");
public static void Main(string[] args)
{
//...
Console.WriteLine("Boolean switch {0} configured as {1}",
boolSwitch.DisplayName, boolSwitch.Enabled.ToString());
if (boolSwitch.Enabled)
{
//...
}
}
Notes to Inheritors:
If you need trace levels, or mechanisms for setting switch levels different from those provided by BooleanSwitch, SourceSwitch and TraceSwitch, you can inherit from Switch. When inheriting from this class, you must implement the SwitchSetting method.