Skip to content

Nullable reference types C# 8.0correctness

Allow use of reference types to be declared nullable or non-nullable.

Unlike value types which always have a default actual value (e.g. 0 for int), reference types by default can be null indicating no value at all.

This can cause NullReferenceExceptions at runtime if the developer forgets to check for null before accessing members of the object.

C# 8.0 introduces an option for the compiler to switch into nullability checking mode and warn the of potential issues.

To enable this mode add the following to your .csproj file:

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

The various options are:

  • enable: Enable nullability checking for all reference types
  • disable: Disable nullability checking for all reference types
  • warnings: Enable nullability checking for all reference types but only warn on violations
  • annotations: Enable nullability checking for all reference types and warn on violations except when the value is assigned to a non-nullable variable

Notes

More information