Search code examples
c#visual-studiovisual-studio-2019c#-8.0nullable-reference-types

How to enable Nullable Reference Types feature of C# 8.0 for the whole project


According to the C# 8 announcement video the "nullable reference types" feature can be enabled for the whole project.

But how to enable it for the project? I did not find any new appropriate option in the Project Properties window in Visual Studio 2019 Preview 1.

Can it be enabled for 'legacy' .csproj projects if the C# language version is changed to 8.0?


Solution

  • To enable Nullable Reference Types for all code in a project, add the following to its .csproj file:

    <PropertyGroup>
      <Nullable>enable</Nullable>
    </PropertyGroup>
    

    Alternatively open the Project Properties UI, search for nullable and select the option you want:

    enter image description here


    To enable this in all projects in the solution, add the property to a Directory.Build.props file instead. You can use such a file to specify other properties across multiple projects too.


    If you're targeting a version of .NET earlier than netcoreapp3.0, you'll also need to set LangVersion to 8 or higher, as Nullable Reference Types were added in C# 8:

    <PropertyGroup>
      <Nullable>enable</Nullable>
      <LangVersion>8.0</LangVersion>
    </PropertyGroup>
    

    For older Visual Studio versions:

    • You must be using at least VS 16.0
    • In 16.0 preview 1, set NullableReferenceTypes to true.
    • From 16.0 preview 2 to 16.1, set NullableContextOptions to enable.
    • From 16.2 preview 1 onwards, use Nullable as above.