Opting into experimental functionality

Using the RequiresPreviewFeatures attribute to create preview functionality

Home DailyDrop

Daily Knowledge Drop

The RequiresPreviewFeatures attribute can be used to flag a specific piece of code as experimental or in preview - this code cannot be used unless the consumer specifically opts into enabling preview features, preventing the preview, potentially unstable code, from being used unwittingly.


Preview feature

Code

To mark a method (or class, property etc) as in preview, it is decorated with the RequiresPreviewFeatures attribute. Here the DoWorkNew method is flagged as in preview:

public class Worker
{
    public void DoWork()
    {
        // do some work the old way
    }

    [RequiresPreviewFeatures()]
    public void DoWorkNew() 
    { 
        // do some work the new one
    }
}

As it stands, trying to use this method:

var worker = new Worker();

worker.DoWorkNew();

will result in the following compiler error:

Using 'DoWorkNew' requires opting into preview features. See https://aka.ms/dotnet-warnings/preview-features for more information.	

To to able to use code marked with the attribute, one specifically needs to opt into preview features.


Project

To opt into preview features, in the csproj file ensure the EnablePreviewFeatures setting is set to true:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnablePreviewFeatures>true</EnablePreviewFeatures>
  </PropertyGroup>
</Project>

With this the code will now compile successfully and be able to leverage preview/experimental features.


Notes

As a library author this is a very useful tool - allowing new experimental functionality to be introduced "safely". Usage of the functionality is semi-controlled, and the consumers are required to make an informed choice to manually opt into using potentially unstable code.


References

Marking API's as obsolete or as experimental

Daily Drop 210: 25-11-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net attribute preview