hamsterbyte

Nullable Reference Types: Eliminating Null Reference Exceptions

Null reference exceptions have plagued developers for decades. C# 8 introduced nullable reference types to help eliminate these errors at compile time.

Enabling Nullable Reference Types

Add to your project file or use a directive:

#nullable enable

Or in your .csproj:

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

Understanding the Syntax

With nullable reference types enabled, reference types are non-nullable by default:

string notNull = "Hello";     // Cannot be null
string? canBeNull = null;     // Can be null

Handling Nullable Values

The compiler helps you handle nulls safely:

public void ProcessName(string? name)
{
    // Compiler warning - 'name' might be null
    // Console.WriteLine(name.Length);
    
    // Safe - null check
    if (name != null)
    {
        Console.WriteLine(name.Length);
    }
    
    // Safe - null-conditional operator
    Console.WriteLine(name?.Length ?? 0);
}

Null-Forgiving Operator

When you know a value isn’t null but the compiler doesn’t:

string? possiblyNull = GetValue();
string definitelyNotNull = possiblyNull!;

Best Practices

  1. Enable nullable reference types in new projects
  2. Avoid the null-forgiving operator unless necessary
  3. Design APIs to avoid nullable returns when possible
  4. Use nullable value types (int?) for optional values

Migration Strategy

For existing projects:

  1. Enable nullable warnings gradually
  2. Start with new code
  3. Fix warnings file by file
  4. Use #nullable enable selectively

Nullable reference types significantly reduce null reference exceptions. While the initial setup requires effort, the long-term benefits are substantial.

Tags: