C# 8.0 Features: Nullable Reference Types Explained

Nullable reference types are the biggest C# 8.0 feature. They help eliminate null reference exceptions at compile time. Here’s how they work.

Enabling Nullable

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

The New Syntax

// Non-nullable (default with feature enabled)
string name = "John";  // Cannot be null

// Nullable 
string? nickname = null;  // Explicitly nullable

// Must check before using
if (nickname != null)
{
    Console.WriteLine(nickname.Length);  // Safe
}

Null Forgiving Operator

// When you know better than the compiler
string? maybeNull = GetValue();
string definitelyNotNull = maybeNull!;  // Trust me

Benefits

  • Compiler warnings for potential null dereferences
  • Documentation of intent in method signatures
  • Catches bugs before runtime

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.