C# 8.0: Nullable Reference Types in Practice

The “Billion Dollar Mistake” – the null reference – is finally being addressed in C# 8.0. Nullable Reference Types (NRT) are not just a compiler check; they are a fundamental shift in how we design software.

Enabling NRT

To enable it, add <Nullable>enable</Nullable> to your .csproj. Prepare for a sea of yellow warnings. Do not suppress them. Fix them.

The Design Philosophy

The goal is to eliminate NullReferenceException from your runtime. If a property can be null, the type system should force you to handle it.

// BAD: The old way
public class User {
    public string Name { get; set; } // Can this be null? Who knows?
}

// GOOD: C# 8.0 Way
public class User {
    public string Name { get; } // Guaranteed to never be null

    public string? MiddleName { get; } // Explicitly nullable

    public User(string name, string? middleName) {
        Name = name ?? throw new ArgumentNullException(nameof(name));
        MiddleName = middleName;
    }
}

Handling DTOs and EF Core

Database entities are tricky because they are often initialized by reflection. For these, initialize properties to default! or string.Empty/null! to tell the compiler “I know what I’m doing, this will be set by the ORM.”

public class Order {
    public string OrderId { get; set; } = null!; // Set by EF Core
}

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.