O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.3. Creating Your Own Custom Switch Class

Problem

The BooleanSwitch and TraceSwitch classes defined in the FCL may not always have the required flexibility or fine-grained control that you need. You want to create you own switch class that provides the level of control and flexibility that you need. For example, creating a class that allows you to set more precise trace levels than those supported by the TraceSwitch class. The TraceSwitch class provides the following tracing levels:

TraceError
TraceWarning
TraceInfo
TraceVerbose

However, you need a finer-grained set of levels, such as the following:

Disable
MinorError
Note
MediumError
Warning
CriticalError

Solution

You can create your own switch class that inherits from System.Diagnostics.Switch and provides the level of control that you need. For example, creating a class that allows you to set more precise trace levels than those supported by the TraceSwitch class involves the following steps:

  1. Define a set of enumerated values that represent the levels to be supported by your switch class:

    public enum AppSpecificSwitchLevel 
    {
        Disable = 0,
        Note = 1,
        Warning = 2,
        MinorError = 3,
        MediumError = 4,
        CriticalError = 5
    }
  2. Define a class, such as AppSpecificSwitch, that inherits from System.Diagnostics.Switch:

    public class AppSpecificSwitch : Switch { protected AppSpecificSwitchLevel level = 0; public AppSpecificSwitch(string displayName, string description) : base(displayName, description) { this.Level = (AppSpecificSwitchLevel)base.SwitchSetting; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required