DEV Community

Hamza
Hamza

Posted on

6 3 3 3 3

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 👋!

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay