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; ...

Get C# Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.