Compatibility Switches

3In the new version of .NET (version 4.6), Microsoft came out with AppContext. This little class has two methods: SetSwitch and TryGetSwitch.

The idea behind these two methods is to allow op-out functionality of new features. If for example, you want to change the format of the logs your library creates. You can have a switch called “Switch.MyLibrary.UseOldLogStyle” that allows the user to keep using the old format. This is great if the end user has some automation parsing the existing logs, and don’t want their parser to break.

It’s easy to use in your library, just use the sample code:


bool useOldLogging
if (!AppContext.TryGetSwitch(“Switch.MyLibrary.UseOldLogStyle”, out useOldLogging))
    useOldLogging = false;
Then you can easily use the useOldLogging variable to decide which methodology to use for logging.
The user simply needs to have the below, in order to activate the switch…

AppContext.SetSwitch("Switch.MyLibrary.UseOldLogStyle", true);
…and they will be able to continue to use their old logging.
I believe that this will make it easier for developers to make changes to their APIs while at the same time reducing the impact that falls on the client using their library.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s