4 ways to enable the latest C# features

The C# language evolves regularly. C# 7.1 is available with Visual Studio 2017 Update 3 (version 15.3). However, the new functionnalities of C# 7.1 are not available by default. By default, the version of C# is the latest major version (currently 7.0). You must explicitly edit the configuration of your projects to set the version of the language.

If you wonder what's new in C# 7.1, you can read more about the new language features on GitHub:

Method 1: Using Light bulb

This is the easiest way. You just have to use a new language feature. Visual Studio will automatically detect you want to use the new version of the language and ask you to update the project:

Enabling C# features using lightbulb

Method 2: Using the project settings window

  1. Open the settings of your project
  2. Select the Build tab
  3. Click the Advanced button
  4. Select the version you want

Enabling C# features using project properties

Method 3: Editing the csproj

You can edit the csproj file directly, and add <LangVersion>latest</LangVersion> or the explicit version <LangVersion>7.1</LangVersion>:

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <RootNamespace>ConsoleApp1</RootNamespace>
    <AssemblyName>ConsoleApp1</AssemblyName>
    <TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <LangVersion>latest</LangVersion>
  </PropertyGroup>

Method 4: Using a prop file

If you want to set a version for all your project at once, you can create a file named Directory.Build.props at the root of your repository. This file contains the list of common properties of your projects:

<Project>
  <PropertyGroup>
    <LangVersion>latest</LangVersion>
  </PropertyGroup>
</Project>

MSBuild will merge your csproj files with this prop one. Therefore, you'll automatically use the LangVersion of this file for all the projects of your solution and the new projects. BTW, you can also configure common properties such as the author, company, project url, etc. You can find an example in the following project: Directory.Build.props

Enjoy this blog? Buy Me A Coffee Donate with PayPal

Comments

Leave a reply