How to build your .NET projects targeting latest version of C#

Aug 3, 2019 | Utkarsh Shigihalli Utkarsh Shigihalli

dotnetcore Azure DevOps

Recently our development team decided to use C# 7.1 language features. However our builds on Azure DevOps started failing quickly. In this quick post we will see how to build your solution targeting the latest version of C# on Azure DevOps.

Here developer is using default literal and the error you might see in your build log is as below.

error CS8107: Feature 'default literal' is not available in C# 7.0. Please use language version 7.1 or greater.

Error in Azure DevOps logs

Cause

The issue was that our agent machines have Visual Studio 2017 v15.9.14 installed and by default it targets major version of C#. This can be confirmed by running below command in Developer Command Prompt.

C# version for Visual Studio

As you can see, the default is set to 7.0 and latest supported is 7.3.

Resolution

We can resolve this error by explicitly instructing the compiler that we would like to use the latest version of the language. Microsoft documentation provides 3 options to override and build your application using required language version.

Editing the project file

You can edit the project file for individual projects and set the LangVersion property as required. In our case latest.

Setting the language version in project file

Setting the langversion compiler option

If you do not want to edit your project file, you can still fix the build by passing -langversion:latest compiler option in the build pipeline in Azure DevOps. For this, go edit the pipeline and under Visual Studio Build task pass the option under MSBuild Arguments section as below.

Setting language version in Visual Studio build step

Configure multiple projects at once

If your source directory contains multiple project and you would like to set the language version for all projects explicitly, you can create Directory.Build.props file that contains the <LangVersion> element.

1
2
3
4
5
<Project>
 <PropertyGroup>
   <LangVersion>preview</LangVersion>
 </PropertyGroup>
</Project>

More here

Conclusion

In this blog post we saw how we can set and use the latest version version of C# when building .NET Core applications. We also saw how we can pass compiler option in Azure DevOps Visual Studio build step if team has already agreed to use the latest version of the C# language.

Hope you found this post useful.

About author
Utkarsh Shigihalli
Utkarsh Shigihalli
Utkarsh is passionate about software development and has experience in the areas of Azure, Azure DevOps, C# and TypeScript. Over the years he has worked as an architect, independent consultant and manager in many countries including India, United States, Netherlands and United Kingdom. He is a Microsoft MVP and has developed numerous extensions for Visual Studio and Azure DevOps.
Comments