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 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: Allow ? annotations and issue nullability warnings
  • disable: No annotations or warnings, matching the behavior before C# 8.0
  • warnings: Issue warnings when code might dereference null, but ? annotations are not allowed (useful as a first migration step)
  • annotations: Allow ? annotations but issue no warnings

You can also change the setting for part of a file with directives such as #nullable enable and #nullable disable.

Code ​

csharp
// With nullable context enabled
string name = GetName();       // Non-nullable, compiler warns if null is assigned
string? nickname = GetAlias(); // Explicitly nullable

if (nickname != null)
    Console.WriteLine(nickname.Length); // No warning, compiler tracks null state
csharp
// Without nullable context
string name = GetName();       // Could be null with no warning
string nickname = GetAlias();  // Could also be null with no warning

if (nickname != null)
    Console.WriteLine(nickname.Length); // Works but compiler offered no help

Notes ​

More information ​

Powered by Intracia