Skip to content

Conversation

gfoidl
Copy link
Member

@gfoidl gfoidl commented Sep 13, 2025

Summary

ATM this page seems to be the only documentation for FeatureSwitchDefinition, thus there should be used best practices.

Here the property's getter was executed on every access, so the AppContext.TryGetSwitch was also called on every access.
This PR changes the property to be read-only (backed by a static readonly field), so in Tier-1 code the JIT can treat the value of the switch as constand and dead-code eliminate some things -- especially there's only one call to AppContext.TryGetSwitch needed.


Internal previews

📄 File 🔗 Preview link
docs/core/whats-new/dotnet-9/runtime.md What's new in the .NET 9 runtime

@gfoidl gfoidl requested a review from a team as a code owner September 13, 2025 15:34
@dotnetrepoman dotnetrepoman bot added this to the September 2025 milestone Sep 13, 2025
@dotnet-policy-service dotnet-policy-service bot added dotnet-fundamentals/svc community-contribution Indicates PR is created by someone from the .NET community. labels Sep 13, 2025
@BillWagner BillWagner requested a review from gewarren September 15, 2025 14:28
@BillWagner
Copy link
Member

@gewarren

I gave this a look, and if TryGetSwitch will always return the same value per run, this is fine. However, if the property could change value during program execution, this change could introduce bugs.

@gfoidl
Copy link
Member Author

gfoidl commented Sep 15, 2025

the property could change value during program execution

In theory that can happen, as AppContext.SetSwitch could be called. This is rare, but not 100 % unlikely.
The majority of cases is to set the flag via RuntimeHostConfigurationOption in the csproj.

Maybe it's best to leave the code sample as is, and add a comment like

// When you are under full control of the flag and the app that will consume it, and
// when the flag value won't be changed during program execution, make this a readonly 
// property to enable further optimizations.

My basic concern with the code as is written in the docs is this:

  • a user has some code around
  • then the user tries out the feature switch in app w/o trimming enabled
  • the user realizes that the relevant piece of code slowed down a lot
  • the user blames the feature switch feature (unjustly)

And that situation should be avoided, especially as there are no other docs at the moment for feature switches.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
community-contribution Indicates PR is created by someone from the .NET community. dotnet-fundamentals/svc
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants