.NET Framework Class Library
Switch Class

Provides an abstract base class to create new debugging and tracing switches.

Namespace:   System.Diagnostics
Assembly:  System (in System.dll)
Syntax
Public MustInherit Class Switch
public abstract class Switch
public ref class Switch abstract
[<[%$TOPIC/k39t4077_en-us_VS_110_2_0_3_0_0%]>]
type Switch =  class end

The Switch type exposes the following members.

Constructors
  NameDescription
Protected method Switch(String, String)Initializes a new instance of the Switch class.
Protected method Switch(String, String, String)Initializes a new instance of the Switch class, specifying the display name, description, and default value for the switch.
Top
Properties
  NameDescription
Public property AttributesGets the custom switch attributes defined in the application configuration file.
Public property DescriptionGets a description of the switch.
Public property DisplayNameGets a name used to identify the switch.
Protected property SwitchSettingGets or sets the current setting for this switch.
Protected property ValueGets or sets the value of the switch.
Top
Methods
  NameDescription
Public method Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCodeServes as the default hash function. (Inherited from Object.)
Protected method GetSupportedAttributesGets the custom attributes supported by the switch.
Public method GetTypeGets the Type of the current instance. (Inherited from Object.)
Protected method MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected method OnSwitchSettingChangedInvoked when the SwitchSetting property is changed.
Protected method OnValueChangedInvoked when the Value property is changed.
Public method ToStringReturns a string that represents the current object. (Inherited from Object.)
Top
Remarks

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( )
    '...
    Console.WriteLine("Boolean switch {0} configured as {1}",
        boolSwitch.DisplayName, boolSwitch.Enabled.ToString())
    If boolSwitch.Enabled = True Then 
        '... 
    End If 
End Sub
private static BooleanSwitch boolSwitch = new BooleanSwitch("mySwitch",
    "Switch in config file");

public static void Main( )
{
    //...
    Console.WriteLine("Boolean switch {0} configured as {1}",
        boolSwitch.DisplayName, boolSwitch.Enabled.ToString());
    if (boolSwitch.Enabled)
    {
        //...
    }
}
private:
    static BooleanSwitch^ boolSwitch = gcnew BooleanSwitch("mySwitch",
        "Switch in config file");

public:
    static void Main( )
    {
        //...
        Console::WriteLine("Boolean switch {0} configured as {1}",
            boolSwitch->DisplayName, ((Boolean^)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.

Examples

The following example shows how to define a new Switch class with four levels of tracing that can be used to trace a call stack. You can use the switch to instrument your application to log each time the method is entered or exited.

The first example creates the enumeration used to set the level of the switch.

' The following are possible values for the new switch. 
Public Enum MethodTracingSwitchLevel
    Off = 0
    EnteringMethod = 1
    ExitingMethod = 2
    Both = 3
End Enum 'MethodTracingSwitchLevel
// The following are possible values for the new switch. 
public enum MethodTracingSwitchLevel
{
    Off = 0,
    EnteringMethod = 1,
    ExitingMethod = 2,
    Both = 3,
}
// The following are possible values for the new switch. 
public enum class MethodTracingSwitchLevel
{
    Off = 0,
    EnteringMethod = 1,
    ExitingMethod = 2,
    Both = 3
};

The following example creates the new switch. The code implements a Level property to set the value of the new switch. Level calls the protected property SwitchSetting that assigns the value to the new switch. This example also implements two assessor properties to get the assigned value of the switch.

Public Class MyMethodTracingSwitch
    Inherits Switch
    Protected outExit As Boolean 
    Protected outEnter As Boolean 
    Protected myLevel As MethodTracingSwitchLevel

    Public Sub New(displayName As String, description As String)
        MyBase.New(displayName, description)
    End Sub 'New 


    Public Property Level() As MethodTracingSwitchLevel
        Get 
            Return myLevel
        End Get 
        Set
            SetSwitchSetting(CInt(value))
        End Set 
    End Property 


    Protected Sub SetSwitchSetting(value As Integer)
        If value < 0 Then
            value = 0
        End If 
        If value > 3 Then
            value = 3
        End If

        myLevel = CType(value, MethodTracingSwitchLevel)

        outEnter = False 
        If value = CInt(MethodTracingSwitchLevel.EnteringMethod) Or _
            value = CInt(MethodTracingSwitchLevel.Both) Then

            outEnter = True 
        End If

        outExit = False 
        If value = CInt(MethodTracingSwitchLevel.ExitingMethod) Or _
            value = CInt(MethodTracingSwitchLevel.Both) Then

            outExit = True 
        End If 
    End Sub 'SetSwitchSetting


    Public ReadOnly Property OutputExit() As Boolean 
        Get 
            Return outExit
        End Get 
    End Property 


    Public ReadOnly Property OutputEnter() As Boolean 
        Get 
            Return outEnter
        End Get 
    End Property 
End Class 'MyMethodTracingSwitch
public class MyMethodTracingSwitch : Switch
{
     protected bool outExit;
     protected bool outEnter;
     protected MethodTracingSwitchLevel level;

     public MyMethodTracingSwitch(string displayName, string description) :
         base(displayName, description)
     {
     }

     public MethodTracingSwitchLevel Level
     {
         get
         {
             return level;
         }
         set
         {
             SetSwitchSetting((int)value);
         }
     }

     protected void SetSwitchSetting(int value)
     {
         if (value < 0)
         {
             value = 0;
         }
         if (value > 3)
         {
             value = 3;
         }

         level = (MethodTracingSwitchLevel)value;

         outEnter = false;
         if ((value == (int)MethodTracingSwitchLevel.EnteringMethod) ||
             (value == (int)MethodTracingSwitchLevel.Both))
         {
             outEnter = true;
         }

         outExit = false;
         if ((value == (int)MethodTracingSwitchLevel.ExitingMethod) ||
             (value == (int)MethodTracingSwitchLevel.Both))
         {
             outExit = true;
         }
     }

     public bool OutputExit
     {
         get
         {
             return outExit;
         }
     }

     public bool OutputEnter
     {
         get
         {
             return outEnter;
         }
     }
 }
public ref class MyMethodTracingSwitch: public Switch
{
protected:
    bool outExit;
    bool outEnter;
    MethodTracingSwitchLevel level;

public:
    MyMethodTracingSwitch( String^ displayName, String^ description )
       : Switch( displayName, description )
    {}

    property MethodTracingSwitchLevel Level
    {
        MethodTracingSwitchLevel get()
        {
            return level;
        }

       void set( MethodTracingSwitchLevel value )
       {
           SetSwitchSetting( (int)value );
       }
    }

protected:
    void SetSwitchSetting( int value )
    {
        if ( value < 0 )
        {
            value = 0;
        }

        if ( value > 3 )
        {
            value = 3;
        }

        level = (MethodTracingSwitchLevel)value;
        outEnter = false;
        if ((value == (int)MethodTracingSwitchLevel::EnteringMethod) ||
            (value == (int)MethodTracingSwitchLevel::Both))
        {
            outEnter = true;
        }

        outExit = false;
        if ((value == (int)MethodTracingSwitchLevel::ExitingMethod) ||
            (value == (int)MethodTracingSwitchLevel::Both))
        {
            outExit = true;
        }
    }

public:
    property bool OutputExit
    {
        bool get()
        {
            return outExit;
        }
    }

    property bool OutputEnter
    {
        bool get()
        {
            return outEnter;
        }
    }
};

The following example creates a new switch in Main. It creates a new switch and assigns it a value. Then, depending on the switch settings, it outputs debugging messages for entering and leaving the method.

Public Class Class1
    ' Create an instance of MyMethodTracingSwitch. 
    Private Shared mySwitch As New _
        MyMethodTracingSwitch("Methods", "Trace entering and exiting method")

    Public Shared Sub Main()
        ' Add the console listener to see trace messages as console output
        Trace.Listeners.Add(New ConsoleTraceListener(True))
        Debug.AutoFlush = True 

        ' Set the switch level to both enter and exit
        mySwitch.Level = MethodTracingSwitchLevel.Both

        ' Write a diagnostic message if the switch is set to entering.
        Debug.WriteLineIf(mySwitch.OutputEnter, "Entering Main")

        ' Insert code to handle processing here... 

        ' Write another diagnostic message if the switch is set to exiting.
        Debug.WriteLineIf(mySwitch.OutputExit, "Exiting Main")
    End Sub 
End Class 'MyClass
public class Class1
{
    /* Create an instance of MyMethodTracingSwitch.*/ 
    static MyMethodTracingSwitch mySwitch =
        new MyMethodTracingSwitch("Methods", "Trace entering and exiting method");

    public static void Main()
    {
        // Add the console listener to see trace messages as console output
        Trace.Listeners.Add(new ConsoleTraceListener(true));
        Debug.AutoFlush = true;

        // Set the switch level to both enter and exit
        mySwitch.Level = MethodTracingSwitchLevel.Both;

        // Write a diagnostic message if the switch is set to entering.
        Debug.WriteLineIf(mySwitch.OutputEnter, "Entering Main");

        // Insert code to handle processing here... 

        // Write another diagnostic message if the switch is set to exiting.
        Debug.WriteLineIf(mySwitch.OutputExit, "Exiting Main");
    }
}
public ref class Class1
{
private:

    /* Create an instance of MyMethodTracingSwitch.*/ 
    static MyMethodTracingSwitch^ mySwitch =
        gcnew MyMethodTracingSwitch( "Methods","Trace entering and exiting method" );

public:
    static void main()
    {
        // Add the console listener to see trace messages as console output
        Trace::Listeners->Add(gcnew ConsoleTraceListener(true));
        Debug::AutoFlush = true;

        // Set the switch level to both enter and exit
        mySwitch->Level = MethodTracingSwitchLevel::Both;

        // Write a diagnostic message if the switch is set to entering.
        Debug::WriteLineIf(mySwitch->OutputEnter, "Entering Main");

        // Insert code to handle processing here... 

        // Write another diagnostic message if the switch is set to exiting.
        Debug::WriteLineIf(mySwitch->OutputExit, "Exiting Main");
    }
};
Version Information

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.