Search code examples
c#visual-studio-2019c#-8.0.net-4.7.2

C# 8 features in .NET Framework 4.7.2


In a c# project targeting .NET Framework 4.7.2 I made a local function static because Visual Studio (16.3.3) suggested it. Everything compiled and worked fine. But when I pushed this on my CI build server with the Visual Studio Build Tools (16.3.3) installed, it complained:

error CS8652: The feature 'static local functions' is currently in Preview and unsupported. To use Preview features, use the 'preview' language version.

What I could figure out is that static local functions are a C# 8 feature and C# 8 is not available for projects targeting .NET Framework 4.7.2. So why did it work on the first place and what can I do to make it compile on the build server?


Solution

  • Some features of C# 8.0 are available in .NET Framework, but not all of them. If you can compile locally, your build server should be able to compile too. But note: C# 8.0 is only officially supported on frameworks implementing .NET Standard 2.1 (which the .NET Framework will never do). So while it might work, there might also be problems.

    Don't use LangVersion preview any more. C# 8.0 was released with VS2019 16.3. Use LangVersion latest (or latestMajor or 8.0) to get C# 8.0 support in a project that doesn't support it by default (see C# language versioning).

    To do that, make sure that your csproj files contain the property <LangVersion>latest</LangVersion>. You need to manually edit the csproj files to do this. The UI to change the language version was disabled in VS2019 16.3 because each target framework now officially only supports a single language version.

    Late edit: If you want to use a C# language feature which isn't supported in your target framework you can check if the NuGet package PolySharp includes it. PolySharp enables the use of many newer C# features which would otherwise not be available in older frameworks.