Skip to main content

How to Turn On a Runtime Switch with AppContext.SetSwitch in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

AppContext.SetSwitch("Greeter.UseFormalGreeting", true) turns on a named switch for the whole app, and any code can check it with AppContext.TryGetSwitch. Libraries read switches like this, so that an app can choose how they behave.

The .NET reference on SetSwitch: Sets the value of a switch. It's called by an application (or a library) to declare the value of a switch (which is always a Boolean value) that a dependent library defines. And on TryGetSwitch: Tries to get the value of a switch.

Syntax​

Syntax
AppContext.SetSwitch("<switchName>", <isEnabled>);
bool <found> = AppContext.TryGetSwitch("<switchName>", out bool <value>);
PartWhat it is
"<switchName>"The switch's name, spelled exactly as the code that reads it spells it
<isEnabled>true to turn the switch on, false to turn it off
<found>What TryGetSwitch returns: true if switchName was set and the isEnabled argument contains the value of the switch; otherwise, false.
out bool <value>The switch's value, or false when it wasn't found

The code that reads a switch decides its name. The Azure SDK, for example, reads one named Azure.Experimental.EnableActivitySource, and its documentation says: Set the Azure.Experimental.EnableActivitySource context switch to true in your app’s code. The example here uses a name of its own.

The Example​

A console app called AppContextSwitch has a Greeter class that reads a switch named Greeter.UseFormalGreeting, the way a library would. The program asks TryGetSwitch about the switch and greets Asha, turns the switch on with SetSwitch, then does both again.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n AppContextSwitch
cd AppContextSwitch
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/AppContextSwitch/AppContextSwitch.csproj:
Determining projects to restore...
Restored /Users/you/source/AppContextSwitch/AppContextSwitch.csproj (in 47 ms).
Restore succeeded.

dotnet new console -n AppContextSwitch creates a folder named AppContextSwitch with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or AppContextSwitch.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the statements that check and set the switch:

Program.cs (checking and setting the switch)
// Before SetSwitch, nobody has set the switch, so TryGetSwitch returns false.
bool found = AppContext.TryGetSwitch(Greeter.FormalSwitch, out bool isEnabled);
Console.WriteLine($"Before: found = {found}, enabled = {isEnabled}");
Console.WriteLine(Greeter.Greet("Asha"));

// Turn the switch on for this app.
AppContext.SetSwitch(Greeter.FormalSwitch, true);

found = AppContext.TryGetSwitch(Greeter.FormalSwitch, out isEnabled);
Console.WriteLine($"After: found = {found}, enabled = {isEnabled}");
Console.WriteLine(Greeter.Greet("Asha"));
  • AppContext.TryGetSwitch(Greeter.FormalSwitch, out bool isEnabled) returns whether the switch was set, and puts its value in isEnabled.
  • AppContext.SetSwitch(Greeter.FormalSwitch, true) turns the switch on. The reference: Calling the AppContext.SetSwitch(String, Boolean) has application scope; that is, it affects only the application.
  • The same check runs before and after SetSwitch, to show what changed.

Then the class that reads the switch, after those statements:

Program.cs (the class that reads the switch)
// Code that reads the switch, the way a library does.
static class Greeter
{
// The switch's name: the code that reads the switch decides it.
public const string FormalSwitch = "Greeter.UseFormalGreeting";

public static string Greet(string name)
{
if (AppContext.TryGetSwitch(FormalSwitch, out bool formal) && formal)
{
return $"Good morning, {name}.";
}

return $"Hi, {name}!";
}
}
  • FormalSwitch keeps the switch's name in one constant, so the code that sets the switch and the code that reads it spell it the same way.
  • AppContext.TryGetSwitch(FormalSwitch, out bool formal) && formal is true only when the switch was set and its value is true. Then Greet answers formally.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Before: found = False, enabled = False
Hi, Asha!
After: found = True, enabled = True
Good morning, Asha.

macOS-style terminal window titled Terminal — AppContextSwitch showing dotnet run printing Before: found = False, enabled = False, Hi, Asha!, After: found = True, enabled = True and Good morning, Asha.

Before SetSwitch, TryGetSwitch found nothing, and Greet used the everyday greeting. After it, the switch was found and on, and the same call to Greet answered Good morning, Asha.

The Complete File​

macOS-style code window titled Program.cs — AppContextSwitch showing TryGetSwitch called before and after AppContext.SetSwitch turns on Greeter.UseFormalGreeting, two calls to Greeter.Greet, and a static Greeter class with the switch name in a constant and a Greet method that checks the switch with TryGetSwitch

Program.cs
// Before SetSwitch, nobody has set the switch, so TryGetSwitch returns false.
bool found = AppContext.TryGetSwitch(Greeter.FormalSwitch, out bool isEnabled);
Console.WriteLine($"Before: found = {found}, enabled = {isEnabled}");
Console.WriteLine(Greeter.Greet("Asha"));

// Turn the switch on for this app.
AppContext.SetSwitch(Greeter.FormalSwitch, true);

found = AppContext.TryGetSwitch(Greeter.FormalSwitch, out isEnabled);
Console.WriteLine($"After: found = {found}, enabled = {isEnabled}");
Console.WriteLine(Greeter.Greet("Asha"));

// Code that reads the switch, the way a library does.
static class Greeter
{
// The switch's name: the code that reads the switch decides it.
public const string FormalSwitch = "Greeter.UseFormalGreeting";

public static string Greet(string name)
{
if (AppContext.TryGetSwitch(FormalSwitch, out bool formal) && formal)
{
return $"Good morning, {name}.";
}

return $"Hi, {name}!";
}
}

Set the Switch in the Project File​

A switch can also be set in the project file. The runtime configuration guide: For runtime configuration settings that don't have a specific MSBuild property, you can use the RuntimeHostConfigurationOption MSBuild item instead. Use the runtimeconfig.json setting name as the value of the Include attribute. An ASP.NET Core guide sets one of its switches there so that it applies before any app code runs.

Add an ItemGroup with the switch to AppContextSwitch.csproj:

AppContextSwitch.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<RuntimeHostConfigurationOption Include="Greeter.UseFormalGreeting" Value="true" />
</ItemGroup>

</Project>

Then replace the statements at the top of Program.cs with these, which don't call SetSwitch, and keep the Greeter class:

Program.cs (the statements, without SetSwitch)
// No SetSwitch here: the project file sets the switch.
bool found = AppContext.TryGetSwitch(Greeter.FormalSwitch, out bool isEnabled);
Console.WriteLine($"found = {found}, enabled = {isEnabled}");
Console.WriteLine(Greeter.Greet("Asha"));
Terminal
dotnet run
Output
found = True, enabled = True
Good morning, Asha.

The switch was on from the start. The guide: When a project is built, an [appname].runtimeconfig.json file is generated in the output directory. Here that file holds the switch:

bin/Debug/net10.0/AppContextSwitch.runtimeconfig.json
{
"runtimeOptions": {
"tfm": "net10.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "10.0.0"
},
"configProperties": {
"Greeter.UseFormalGreeting": true,
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
}
}
}

Common Mistakes​

MistakeWhat happensDo this instead
A typo in the switch's nameNothing fails: after SetSwitch("Greeter.UseFormalGreting", true), one letter short, Greet still answered Hi, Asha!Spell the name exactly as the reading code does. Keeping it in one constant, as Greeter.FormalSwitch does, helps
Setting the switch after the code has read itA Greeter that read the switch once, into a static readonly field, kept its first answer: Hi, Asha! came back before and after SetSwitchSet switches at the very start of the program, before any code that reads them, or in the project file

FAQ​

How do I turn a switch off again?​

Call SetSwitch with false. The switch stays set, now with the value false:

Program.cs
AppContext.SetSwitch("Greeter.UseFormalGreeting", true);
AppContext.SetSwitch("Greeter.UseFormalGreeting", false);

bool found = AppContext.TryGetSwitch("Greeter.UseFormalGreeting", out bool isEnabled);
Console.WriteLine($"found = {found}, enabled = {isEnabled}");
Output
found = True, enabled = False

Conclusion​

Turn a switch on with AppContext.SetSwitch("<name>", true) at the start of the program, or with a RuntimeHostConfigurationOption in the project file, and read it with AppContext.TryGetSwitch. Spell the name exactly as the reading code does: a misspelled switch doesn't fail, it's just a switch that nothing reads.

Additional Resources​