What is Feature Switching in .NET 9 ?!

1hamzabek

Hamza

Posted on November 22, 2024

What is Feature Switching in .NET 9 ?!

Today's topic is going to be about .Net 9 . Covering new features with examples 👌.

Let's get started!

Feature switching

So Feature Switching is basically like Feature Flagging, But with Microsoft built-in support.

That's awesome isn't ?

Imagine we have a class and a method called DoThing

public class Features
{
  internal static void DoThing()
  {
   Console.WriteLine("Do a Thing");
  }
}
Enter fullscreen mode Exit fullscreen mode

So i want to enable this feature for specific execution or API Testing etc... Here it comes the Feature Switching.

internal static bool IsFeatureEnabled =>
       AppContext.TryGetSwitch("Feature.IsEnabled" , out var IsEnabled) && IsEnabled;
Enter fullscreen mode Exit fullscreen mode

"Feature.IsEnabled" This is the Switch's name.
out var IsEnabled This is declaring a variable IsEnabled That will store the result of the method. The out Indicates that the value will be assigned to this vartiable.

Let's get back to our main class and try to call this method

using FeatureSwitching;

if(Feature.IsEnabled)
{
  Features.DoThing();
}

//output : Do a Thing

Enter fullscreen mode Exit fullscreen mode

Here we still get the method called, Because i have to specify whether i want the method to be Enabled or Disabled (It's automatically Enabled)

How can we market and specify a method ?!

Let's add this to the feature class

[FeatureSwitchDefinition(Feature.IsEnabled)]
Enter fullscreen mode Exit fullscreen mode

Make sure to use the Method's name "Feature.IsEnabled"

Now, Let's move to .csproj and specify the method 🏃‍♂️:

<ItemGroup>
     <RuntimeHostConfigurationOption Include="Feature.IsEnabled" Value="False" Trim="True"/>
</ItemGroup>
Enter fullscreen mode Exit fullscreen mode

When you try now to run the code, you aren't going to see output because the switch is Disabled, other words False!

Try enabling the switch and let me know what you see!

Key Benefits 🗝️ :

  1. Backward Compatibility

  2. Granular Control

  3. Configuration Management

Here's the end of today's article. See you later guys 👋!

💖 💪 🙅 🚩
1hamzabek
Hamza

Posted on November 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What is Feature Switching in .NET 9 ?!