Craftsman at Work

I'm Artur Karbone, coding software architect and independent IT consultant and this is my blog about craftsmanship, architecture, distributed systems, management and much more.

C# Language Versions: How to Override the default

There is a mapping between the project's target framework and the C# language version, which is based on the following rules.
Find more details in C# Language Reference :

Target Framework C# Version
.NET 8.x C# 12
.NET 7.x C# 11
.NET 6.x C# 10
.NET 5.x C# 9.0
NET Core 3.x C# 8.0
NET Core 2.x C# 7.3
NET Standard 2.1 C# 8.0
NET Standard 2.0 C# 7.3
NET Standard 1.x C# 7.3
.NET Framework C# 7.3

To figure out the current version for whatever reason right click Project-> Properties -> Build -> Advanced:

If there is a need to stick to some specific version there are multiple ways, to achieve that.

Override #1

To specify the C# version of your choice, edititing the project file:

LangVersion is the element you are looking for:

<PropertyGroup>  
   <LangVersion>preview</LangVersion>
</PropertyGroup>  

or

<PropertyGroup>  
   <LangVersion>12.0</LangVersion>
</PropertyGroup>  

Override #2

Another useful option is to leverage Visual Studio Bulb Assistant. When using a new C# 12 feature for instance being on a previous C# version, there will be a compilation error. In addition to that Visual Studio 2022 will provide an easy way to upgrade to the needed C# version with just a single click:

Override #3

Configure multiple projects in your solution directory by editing Directory.Build.props. The syntax is the same as for the project file:

<Project>  
 <PropertyGroup>
   <LangVersion>preview</LangVersion>
 </PropertyGroup>
</Project>  

Override #4

Specify -langversion option, calling csc.exe.

comments powered by Disqus