Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can we create nullable type based on reference type?

Nullable reference types aren't new class types, but rather annotations on existing reference types. The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type.

Are nullable types reference types in C#?

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.) So, no they're not reference types.

Where do we use nullable type?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.


In Visual Studio 16.2 (from preview 1) the property name is changed to Nullable, which is simpler and aligns with the command line argument.

Add the following properties to your .csproj file.

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

If you're targeting netcoreapp3.0 or later, you don't need to specify a LangVersion to enable nullable reference types.


For older Visual Studio versions:

  • From 16.0 preview 2 to 16.1, set NullableContextOptions to enable.
  • In 16.0 preview 1, set NullableReferenceTypes to true.

Note that this setting is changed between VS 2019 preview 1 and preview 2. With preview 2 or 3, you need this in your .csproj:

<PropertyGroup>
  <LangVersion>8.0</LangVersion>
  <NullableContextOptions>enable</NullableContextOptions>
</PropertyGroup>

The <NullableReferenceTypes> mentioned in the earlier answer (which, when I originally wrote this answer on 4th Feb 2019, had been marked as the accepted answer) was correct at the time that answer was written, but it is no longer recognized.


In addition to @DrewNoakes accepted answer, note that the nullable property can be set for all projects at once by adding a file called Directory.Build.props in the folder that contains your .sln file.

Just define your Directory.Build.props file like this:

<Project>

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

</Project>

You will need to restart Visual Studio for this to take effect.

More about Directory.Build.props.


Worth noting that, by now, this is also an exposed setting in a project's Properties page:

"Build" tab shows "Nullable" setting

At least in VS2019 16.6+.