Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 182 ยท Null Safety and Errors

Nullable Reference Types

Learn C# nullable reference types - string versus string?, compiler flow analysis, the null-forgiving operator, nullable attributes, required members, and how to migrate an old codebase safely.

Tony Hoare, who invented the null reference in 1965, later called it his "billion-dollar mistake". In C# any variable of a class type can hold null, and the first time you call a method on it the program crashes with a NullReferenceException. The compiler used to know nothing about this. Nullable reference types (C# 8, on by default in new projects since .NET 6) change that: you tell the compiler which references may be null and which may not, and it warns you when your code contradicts itself.

This is not a runtime feature. No new type is created, nothing is checked while the program runs, and string? and string are the same type at runtime. It is a static analysis layer that moves a whole class of crashes from "a user hits it in production" to "a yellow squiggle while typing". Our editor compiles with nullable checking enabled, so every example below shows the real warnings.

Two kinds of reference: string and string?

With the feature on, a plain reference type means never null and a type with ? means may be null:

C# The compiler tracks which references may be null (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last two lines compile (warnings, not errors) and the program then crashes with a NullReferenceException, but the compiler has told you twice, in advance. The messages are CS8600: Converting null literal or possible null value to non-nullable type for assigning null to name, and CS8602: Dereference of a possibly null reference for nickname.Length. Treat warnings as errors in real projects (<TreatWarningsAsErrors> or <WarningsAsErrors>nullable</WarningsAsErrors>) so they cannot be ignored.

Note that int? is a different thing: it is Nullable<int>, a real struct (see Nullable Value Types). string? is only an annotation.

Turning the feature on

In a project file you enable it with one property:

XML
<!-- MyApp.csproj: read-only; the editor on this page already uses this setting -->
<PropertyGroup>
  <Nullable>enable</Nullable>
</PropertyGroup>

Other values are disable (the old world where nothing is tracked), warnings (analysis without annotations) and annotations (the reverse). Inside a file, the directive #nullable switches modes locally, which is the tool for migrating code gradually:

C# #nullable disable switches the analysis off for a region

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

#nullable restore returns to the project setting. In oblivious code (disable) a reference is neither "never null" nor "maybe null", the compiler stays silent about it.

Flow analysis: the compiler follows your code

The compiler does not simply look at the declared type. It tracks the null-state of each variable at each line: maybe-null or not-null. A null check changes the state, so you do not have to restate it.

C# A check makes the compiler happy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Several constructs update the state: is null / is not null, == null, ?., ??, ??=, pattern matching, and string.IsNullOrEmpty(x)-style checks that carry attributes (see below). Early return, throw or continue on null also counts: after if (x is null) return;, the compiler knows x is not null for the rest of the method.

Where the analysis gives up

Flow analysis works inside one method and is deliberately simple. It cannot know what another method does to a field, or whether a property returns the same value twice, so it sometimes warns about code you know is safe (and, more rarely, stays quiet about code that is not). It is a safety net, not a proof. When it is wrong about your code, you need the next tool.

The null-forgiving operator !

A postfix ! says "trust me, this is not null here". It suppresses the warning and does nothing at runtime.

C# ! silences the warning, not the crash (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

No compile-time message appears, and the run ends with System.NullReferenceException: Object reference not set to an instance of an object. The operator moved the risk from the compiler's shoulders to yours.

Use ! rarely and only when you have information the compiler lacks: a value set by a framework before your code runs, a dictionary lookup just guarded by ContainsKey, a test that deliberately provides a value. If you find yourself adding ! everywhere, the design needs a fix. Better alternatives are a real null check with a helpful exception, or the required / constructor routes below. For example, ArgumentNullException.ThrowIfNull(x) both checks at runtime and teaches the compiler:

C# ThrowIfNull is a check the compiler understands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Fields and properties must be initialized

A non-nullable field or property that is not assigned in the constructor produces CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor. You have four honest ways to resolve it:

C# Four ways to satisfy CS8618

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

required (C# 11) forces every object initializer to set the member, which is ideal for DTOs and for types created by deserializers or ORMs that call a parameterless constructor. If you really must satisfy the compiler and promise an initializer later (for example a dependency-injected property), the last-resort spelling is = null!;. It is honest only if something truly assigns the value.

Generic code and constraints

A type parameter T can be a nullable or non-nullable type, so T? needs care. where T : notnull forbids nullable arguments; where T : class? allows them; T? on an unconstrained parameter means "maybe-default". For an unconstrained T, default is null for reference types and zero for value types, which is why Get below returns TValue?:

C# default, T and notnull

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Attributes that describe null behavior

Sometimes a method's null behavior cannot be written with ? alone. The System.Diagnostics.CodeAnalysis attributes fill the gap, and the BCL uses them everywhere:

Attribute Meaning
[NotNullWhen(true)] on an out parameter the value is not null when the method returns true (the TryGetValue shape)
[MaybeNullWhen(false)] the value may be null when the method returns false
[NotNull] the output is not null even though its type says ?
[MaybeNull] the output may be null even though its type is non-nullable (e.g. generic T)
[DoesNotReturn] the method always throws or exits, so code after it is unreachable
[MemberNotNull(nameof(_x))] after this method returns, the field _x is not null
[AllowNull] / [DisallowNull] setters accept (or reject) null
C# Teaching the compiler about your own Try method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Without [NotNullWhen(true)], user.Length would warn because the parameter type is string?. With it, the if is enough.

A practical migration plan

Turning the feature on in a ten-year-old solution can produce thousands of warnings. A sensible order:

  1. Enable <Nullable>enable</Nullable> per project, starting with leaf libraries, or begin with warnings mode.
  2. Annotate the public surface first: parameters and return types. Callers benefit immediately.
  3. Replace = null! and ! with real checks, required or constructors as you go.
  4. Use #nullable disable around generated code, then remove it file by file.
  5. Finally set WarningsAsErrors for nullable warnings so regressions fail the build.

Be careful with libraries that still rely on null as a meaningful value. Annotate those as T? instead of fighting the signature. A compiler warning is information: it usually points to a real unhandled case.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. At runtime, what is the difference between string and string?

    Nullable reference types are annotations. Both are the same System.String type, and nothing stops a null from getting into a string at runtime (for example from reflection or oblivious code).
  2. 2. What does the ! operator do in input!.Length when input is null?

    The null-forgiving operator only changes the compiler's view. At runtime the dereference of null still fails.
  3. 3. Which is the best fix for CS8618 on a DTO property that a deserializer fills in after calling a parameterless constructor?

    required (C# 11) makes every object initializer set the member, so the property is non-null by construction and no warnings are hidden.
  4. 4. What does [NotNullWhen(true)] on an out string? parameter tell the compiler?

    It describes the relation between the return value and the out parameter, so code inside if (TryX(out var v)) can use v without a warning.
  5. 5. After the statement if (text is null) return; what does the compiler assume about text?

    Flow analysis follows the early exit, so on the path that continues, text must be non-null.

Summary

  • With nullable enabled, T means "never null" and T? means "may be null"; the feature is a compile-time analysis, not a runtime type.
  • The compiler follows your null checks (is null, ?., ??, early returns) and warns when you dereference a maybe-null value or assign null to a non-nullable.
  • ! silences the warning only; use it sparingly. Prefer real checks such as ArgumentNullException.ThrowIfNull.
  • Make non-nullable members valid by construction: constructor parameters, defaults or required.
  • Attributes such as [NotNullWhen], [MaybeNull], [DoesNotReturn] and [MemberNotNull] describe patterns that ? cannot.
  • Migrate gradually with #nullable, annotate public APIs first and make nullable warnings errors at the end.

Next: Null-Handling Operators