Nullable reference types

suggest change

Before C# 8 every reference type could be null, and the compiler couldn't tell you when you forgot to check. The result was the most common .NET bug, the NullReferenceException.

C# 8 added nullable reference types (NRT). When the feature is on:

This is a compile-time feature only. string and string? are the same System.String at runtime, nothing is checked when the program runs, and the problems are reported as warnings, not errors.

Don't confuse it with nullable value types. int? is shorthand for Nullable<int>, a real struct with HasValue and Value. string? is the same type as string plus an annotation for the compiler.

The examples are .NET 10 / C# 14 file-based programs, run with dotnet run app.cs. The warnings shown are the real compiler output, with the directory part of the path removed.

Turning it on

Projects created with dotnet new since .NET 6 enable it in the .csproj:

<PropertyGroup>
  <TargetFramework>net10.0</TargetFramework>
  <Nullable>enable</Nullable>
</PropertyGroup>

File-based programs (dotnet run app.cs) have it on by default too. Older projects that don't set <Nullable> have it off.

<Nullable> takes one of four values, which control two separate things: whether ? on a reference type is allowed (annotations) and whether the compiler reports null warnings (warnings):

Value Annotations (string?) Warnings
enable yes yes
warnings no yes
annotations yes no
disable (default) no no

With disable, writing string? gives warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Once a project has no null warnings left, make new ones fail the build so they don't come back:

<WarningsAsErrors>nullable</WarningsAsErrors>

The nullable group covers all the nullable warnings (CS8600, CS8602, CS8618 and the rest). <TreatWarningsAsErrors>true</TreatWarningsAsErrors> also works, but it applies to every warning.

string vs string?

string name = "Ada";       // non-nullable: should never be null
string? nickname = null;   // nullable: null is a normal value

Console.WriteLine(name.Length);      // fine
Console.WriteLine(nickname.Length);  // warning CS8602

name = null;                         // warning CS8600
basics.cs(5,19): warning CS8602: Dereference of a possibly null reference.
basics.cs(7,8): warning CS8600: Converting null literal or possible null value to non-nullable type.

The program still compiles, and when it runs it crashes on line 5 exactly as it would without the feature:

3
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.<Main>$(String[] args) in basics.cs:line 5

The rules are simple:

The warnings you'll see most often:

Warning Meaning
CS8600 Converting null literal or possible null value to non-nullable type
CS8601 Possible null reference assignment (to a field, property or array element)
CS8602 Dereference of a possibly null reference
CS8603 Possible null reference return
CS8604 Possible null reference argument for parameter
CS8618 Non-nullable field/property must contain a non-null value when exiting constructor
CS8625 Cannot convert null literal to non-nullable reference type

Flow analysis

A string? variable isn't "always nullable". The compiler tracks a null state for every variable, either "not null" or "maybe null", and updates it as the code runs: null checks, assignments, patterns and operators all change it. None of the lines below produce a warning:

string? input = Console.ReadLine();     // returns string?

// 1. A null check makes the variable "not null" inside the branch
if (input != null)
    Console.WriteLine($"1: {input.Length}");

// 2. Early return/throw: not null for the rest of the method
void Greet(string? name)
{
    if (string.IsNullOrEmpty(name))
        return;
    Console.WriteLine($"2: Hello, {name.ToUpper()}");
}
Greet("ada");

// 3. Patterns
object o = "text";
if (o is string s)
    Console.WriteLine($"3: {s.Length}");
if (input is not null)
    Console.WriteLine($"3: {input.Trim()}");

// 4. ?? and ??= produce a non-null value
string city = input ?? "unknown";
Console.WriteLine($"4: {city.Length}");
input ??= "default";
Console.WriteLine($"4: {input.Length}");

// 5. ?. returns a nullable result
int? len = input?.Length;
Console.WriteLine($"5: {len}");

// 6. Assigning a non-null value changes the state
string? maybe = null;
maybe = "now set";
Console.WriteLine($"6: {maybe.Length}");

With hello typed on stdin:

1: 5
2: Hello, ADA
3: 4
3: hello
4: 5
4: 5
5: 5
6: 7

string.IsNullOrEmpty in case 2 works because the framework annotates its parameter with [NotNullWhen(false)] (see the attributes section below). Most of the .NET API is annotated, so Console.ReadLine() returns string?, Dictionary.TryGetValue tells the compiler when its out value is set, and so on.

The operators used above are covered in Null-Coalescing Operator and Null-conditional Operators.

Where flow analysis is wrong

The analysis is designed not to bury you in warnings, so it's optimistic in a few places. It doesn't follow method calls: after a null check on a field, the field stays "not null" even if a method you call sets it back to null:

var c = new Customer();
c.Run();

class Customer
{
    private string? _email = "ada@example.com";

    public void Run()
    {
        if (_email != null)
        {
            Reset();                         // sets _email to null...
            Console.WriteLine(_email.Length); // ...but no warning here
        }
    }

    private void Reset() => _email = null;
}

No warnings, and a crash:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Customer.Run() in holes.cs:line 13
   at Program.<Main>$(String[] args) in holes.cs:line 2

Arrays and default structs are the other big holes. A new string[] is full of nulls, and fields of a default struct are null, but the types say otherwise:

string[] names = new string[3];        // three nulls, typed as string
Console.WriteLine(names[0] is null);   // True, no warning

Point p = default;                     // Label is null
Console.WriteLine(p.Label is null);    // True, no warning

struct Point
{
    public string Label;
    public Point(string label) => Label = label;
}
True
True

Code in multithreaded programs has the same problem: the analysis assumes no other thread changes a field between your check and your use. If that can happen, copy the field to a local variable first and check the local.

Fields, properties and constructors

A non-nullable field or property must have a non-null value by the time every constructor finishes. Otherwise you get CS8618:

class User
{
    public string Name { get; set; }   // CS8618
    public string Email;               // CS8618
}
ctor.cs(3,19): warning CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
ctor.cs(4,19): warning CS8618: Non-nullable field 'Email' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the field as nullable.

Depending on what the member means, there are four fixes:

var a = new User2("Ada") { Phone = null };
var b = new User3 { Name = "Grace" };
var c = new User4("Linus");
Console.WriteLine($"{a.Name} {a.Role} {a.Phone ?? "-"} | {b.Name} | {c.Name}");

class User2(string name)
{
    public string Name { get; } = name;              // from the constructor
    public string Role { get; set; } = "member";     // initializer
    public string? Phone { get; set; }               // optional: nullable
}

class User3
{
    public required string Name { get; init; }      // caller must set it
}

class User4
{
    public string Name { get; private set; }

    public User4(string name) => SetName(name);      // CS8618: compiler doesn't look inside SetName

    private void SetName(string name) => Name = name;
}
ctor2.cs(22,12): warning CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
Ada member - | Grace | Linus
  1. Set it in the constructor or with an initializer (User2).
  2. Make it nullable if "no value" is a valid state (Phone). Then every reader has to deal with null, so don't do it just to silence the warning.
  3. Mark it required (C# 11). The object can be created with an object initializer, and the compiler forces every caller to set the property.
  4. Use [MemberNotNull] when a helper method does the initialization. The compiler only looks at the constructor body, so User4 gets a warning even though Name is always set. The attributes section shows the fix.

required and nullability

required and nullable annotations answer different questions. required means "the caller must assign it", the type says whether null is an acceptable value:

var a = new Account { Name = "Ada", Manager = null };  // fine: Manager is required but nullable
var b = new Account { Name = null, Manager = null };   // CS8625
Console.WriteLine($"{a.Name} {a.Manager ?? "(none)"} {b.Name is null}");

class Account
{
    public required string Name { get; init; }      // must be set, must not be null
    public required string? Manager { get; init; }  // must be set, null is a valid answer
}
req2.cs(2,30): warning CS8625: Cannot convert null literal to non-nullable reference type.
Ada (none) True

Forgetting a required member is an error, not a warning:

var u = new User3();   // error CS9035
req.cs(1,13): error CS9035: Required member 'User3.Name' must be set in the object initializer or attribute constructor.

The null-forgiving operator !

A postfix ! tells the compiler "I know this isn't null" and turns off the warning for that expression:

var users = new Dictionary<int, string> { [1] = "Ada" };

string? Lookup(int id) => users.GetValueOrDefault(id);

// We "know" user 1 exists, so we silence the warning with !
string first = Lookup(1)!;
Console.WriteLine(first.ToUpper());

// ! changes nothing at runtime: user 2 doesn't exist
string second = Lookup(2)!;
Console.WriteLine(second.ToUpper());
ADA
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.<Main>$(String[] args) in bang.cs:line 11

No warnings at all, and a crash. ! generates no code: it doesn't check for null and doesn't throw a better exception. Every ! is a promise you have to keep yourself, so use it rarely:

If you write ! often, the annotations are probably wrong. Make the type nullable and handle null, or fix the API so it doesn't return null.

Generics

In generic code T can be a reference type, a nullable reference type or a value type, so T? has a special meaning for an unconstrained T: "T, or default(T)".

// Unconstrained T: T? means "T, or default(T)"
static T? FirstOrDefault<T>(List<T> items) => items.Count > 0 ? items[0] : default;

string? s = FirstOrDefault(new List<string>());   // null
int i = FirstOrDefault(new List<int>());          // for a value type T? is just T: 0
int? j = FirstOrDefault(new List<int?>());        // null
Console.WriteLine($"s={s ?? "null"} i={i} j={j?.ToString() ?? "null"}");

var ok = new Cache<string, string?>();             // values may be null
ok.Add("k", null);
var bad = new Cache<string?, string>();            // CS8714: keys must not be null

class Cache<TKey, TValue> where TKey : notnull
{
    private readonly Dictionary<TKey, TValue> _items = new();
    public void Add(TKey key, TValue value) => _items[key] = value;
}
gen.cs(11,21): warning CS8714: The type 'string?' cannot be used as type parameter 'TKey' in the generic type or method 'Cache<TKey, TValue>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint.
s=null i=0 j=null

Note that for List<int>, T? doesn't turn into int?: the method returns 0, not null.

The constraints related to nullability:

Constraint Allows
(none) any type, nullable or not
where T : notnull non-nullable reference types and non-nullable value types (Dictionary<TKey, TValue> uses it for keys)
where T : class non-nullable reference types only
where T : class? nullable or non-nullable reference types
where T : struct non-nullable value types; here T? is Nullable<T>

Attributes for null-state analysis

A signature like bool TryFind(int id, out string? name) can't say that name isn't null when the method returns true. The attributes in System.Diagnostics.CodeAnalysis describe this kind of contract, so callers don't need !:

using System.Diagnostics.CodeAnalysis;

var repo = new UserRepo();

// [NotNullWhen(true)]: after a true result, the out value is not null
if (repo.TryFind(1, out string? name))
    Console.WriteLine($"found {name.ToUpper()}");

// [NotNullIfNotNull]: non-null in, non-null out
string trimmed = Normalize("  Ada ");
string? nothing = Normalize(null);
Console.WriteLine($"[{trimmed}] [{nothing ?? "null"}]");

// [MemberNotNull]: the helper guarantees the field is set
var conn = new Connection("db.local");
Console.WriteLine(conn.Host.Length);

// [DoesNotReturn]: code after the call is unreachable, so value is known non-null
string? config = Environment.GetEnvironmentVariable("PATH");
if (config is null) Fail("PATH not set");
Console.WriteLine(config.Length > 0);

[return: NotNullIfNotNull(nameof(s))]
static string? Normalize(string? s) => s?.Trim();

[DoesNotReturn]
static void Fail(string message) => throw new InvalidOperationException(message);

class UserRepo
{
    private readonly Dictionary<int, string> _users = new() { [1] = "Ada" };

    public bool TryFind(int id, [NotNullWhen(true)] out string? name) =>
        _users.TryGetValue(id, out name);
}

class Connection
{
    public string Host { get; private set; }

    public Connection(string host) => SetHost(host);   // no CS8618 any more

    [MemberNotNull(nameof(Host))]
    private void SetHost(string host) => Host = host.ToLowerInvariant();
}
found ADA
[Ada] [null]
8
True

This builds with no warnings. Remove the four attributes and you get four: CS8602 on name.ToUpper(), CS8600 on string trimmed = ..., CS8602 on config.Length and CS8618 on the Connection constructor.

Properties can have different rules for the getter and the setter. With [AllowNull] a setter accepts null (and replaces it with a default), while the getter still never returns null:

using System.Diagnostics.CodeAnalysis;

var doc = new Document();
doc.Title = null;                     // allowed by [AllowNull]
Console.WriteLine(doc.Title.Length);  // getter is still non-null
Console.WriteLine(doc.Title);

class Document
{
    private string _title = "untitled";

    [AllowNull]
    public string Title
    {
        get => _title;
        set => _title = value ?? "untitled";
    }
}
8
untitled

The full set:

Attribute Applies to Meaning
[AllowNull] input (parameter, setter) null is accepted even though the type is non-nullable
[DisallowNull] input null is not accepted even though the type is nullable
[MaybeNull] output (return, out, getter) may return null even though the type is non-nullable
[NotNull] output, ref parameter won't be null after the call even though the type is nullable (for example a ThrowIfNull(object? x) helper)
[NotNullWhen(bool)] out/parameter not null when the method returns the given bool (TryGet..., IsNullOrEmpty)
[MaybeNullWhen(bool)] out parameter may be null when the method returns the given bool (TryGetValue(..., [MaybeNullWhen(false)] out TValue value))
[NotNullIfNotNull(name)] return, parameter not null if the named parameter isn't null
[MemberNotNull(names)] method, property the listed members are not null after the call
[MemberNotNullWhen(bool, names)] method, property the listed members are not null when it returns the given bool ([MemberNotNullWhen(true, nameof(Value))] bool HasValue)
[DoesNotReturn] method never returns normally (always throws)
[DoesNotReturnIf(bool)] parameter doesn't return if the argument has the given value (Debug.Assert)

You'll mostly need these when writing libraries or helpers. In application code, [NotNullWhen(true)] for Try methods and [MemberNotNull] for initialization helpers cover most cases.

#nullable directives

The <Nullable> project setting can be overridden for a part of a file with #nullable:

#nullable disable
static string OldApi() => null;     // no warning: nullable context is off
#nullable restore

string a = OldApi();                 // no warning: result is "oblivious"
Console.WriteLine(a?.Length ?? -1);

#nullable disable warnings
string b = null;                     // annotations still on, warnings off
#nullable restore warnings

string c = null;                     // CS8600
Console.WriteLine($"{b ?? "b"} {c ?? "c"}");
directives.cs(12,12): warning CS8600: Converting null literal or possible null value to non-nullable type.
-1
b c

Types declared where annotations are disabled are oblivious: the compiler doesn't know whether they can be null, so it gives no warnings for them in either direction. Libraries compiled without NRT look the same way to your code.

Many of the older examples in this book start with #nullable disable. They were written before NRT existed, and the directive lets them compile without warnings under modern project defaults. In new code, prefer fixing the warnings to disabling them.

Nullability at runtime

Annotations are stored in metadata ([Nullable] and [NullableContext] attributes the compiler generates), so reflection-based code can read them. Nothing enforces them, though, and a caller with NRT turned off, or one using !, can still pass null:

#:property PublishAot=false
using System.Reflection;
using System.Text.Json;

// 1. string? is not a separate type: the annotation is stored as metadata
var ctx = new NullabilityInfoContext();
foreach (var p in typeof(Person).GetProperties())
    Console.WriteLine($"{p.Name,-6} {ctx.Create(p).WriteState}");

// 2. Public APIs should still check arguments at runtime
try { Greet(null!); }
catch (ArgumentNullException e) { Console.WriteLine(e.Message); }

// 3. System.Text.Json ignores annotations unless you opt in (.NET 9+)
string json = """{"Name":null,"Email":null}""";
var loose = JsonSerializer.Deserialize<Person>(json)!;
Console.WriteLine($"default: Name is null = {loose.Name is null}");

var strict = new JsonSerializerOptions { RespectNullableAnnotations = true };
try { JsonSerializer.Deserialize<Person>(json, strict); }
catch (JsonException e) { Console.WriteLine(e.Message); }

static void Greet(string name)
{
    ArgumentNullException.ThrowIfNull(name);
    Console.WriteLine($"Hello, {name}");
}

class Person
{
    public string Name { get; set; } = "";
    public string? Email { get; set; }
}
Name   NotNull
Email  Nullable
Value cannot be null. (Parameter 'name')
default: Name is null = True
The property or field 'Name' on type 'Person' doesn't allow setting null values. Consider updating its nullability annotation. Path: $.Name | LineNumber: 0 | BytePositionInLine: 12.

#:property PublishAot=false is needed because file-based programs are AOT-compatible by default, which turns off reflection-based JSON serialization. A normal project doesn't need it.

Takeaways:

Migrating an existing project

Enabling NRT on a large codebase can produce hundreds of warnings at once. A gradual approach works better:

  1. Start with warnings only. Set <Nullable>warnings</Nullable> in the project. You get warnings for code that clearly dereferences null (for example values returned by annotated .NET APIs such as Console.ReadLine()), without having to annotate anything yet.
  2. Enable it file by file. Alternatively, keep the project at disable and add #nullable enable at the top of files as you convert them. Or set the project to enable and put #nullable disable at the top of every file that isn't converted yet, then delete the directives one by one.
  3. Start with leaf code. Convert files that don't depend on other unconverted code first: models, utilities, then services, then the UI or API layer. When you annotate a type, its callers get correct information.
  4. Decide for each member what null means. For each warning, ask whether null is a valid value. If it is, make the type nullable and handle it at the use sites. If not, make sure it's initialized (constructor, initializer, required) and keep the type non-nullable. Avoid sprinkling ! and = null! to make warnings go away; they hide exactly the bugs the feature is meant to find.
  5. Turn on WarningsAsErrors for nullable once a project is clean, so new code stays clean.

Overrides and interface implementations must agree with the base declaration. If an interface says string? Find(int id) and your implementation returns string, that's fine (a narrower return type), but accepting string where the interface accepts string? gives warnings such as CS8767 (nullability of reference types in type of parameter doesn't match implicitly implemented member). Convert interfaces and base classes together with their implementations.

Summary

For a different approach that makes "no value" explicit in the type itself, see Avoid Null References.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents