Designing for Nullability in C#

Nullable Reference Types (NRT) are enabled by default in .NET 6 templates. It’s time to stop fighting the warnings and embrace the design philosophy.

The Golden Rule

“Design your types to be initialized fully on construction.”

Most NRT warnings come from models that are partially initialized or set via property injection later. If a property can be null, mark it `string?`. If it shouldn’t be null, force it in the constructor.

// Bad
public class Customer {
    public string Name { get; set; } // Warning: Non-nullable property uninitialized
}

// Good
public class Customer {
    public string Name { get; }
    
    public Customer(string name) {
        Name = name ?? throw new ArgumentNullException(nameof(name));
    }
}

// Good (for EF Core / Serialization that needs empty ctor)
public class Customer {
    public string Name { get; set; } = string.Empty; // Default to valid state
}

Generics and Nullability

Use `where T : notnull` or `class?` constraints to be explicit about what your generic methods handle.


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.