Lesson 6 of 24

In progress

Course progress

C# and .NET

Nullable reference types

Turn on nullable annotations, understand the warnings, and use the operators and attributes that make null handling explicit.

Tony Hoare called null his billion-dollar mistake. C#’s response is not to remove it but to make the compiler track it, so a possible null is visible in the type rather than discovered in production.

What you will learn

  • Read and act on nullable warnings.
  • Use ?, !, ?. and ?? without fighting the compiler.
  • Know when the annotations stop protecting you.

Turning it on

<Nullable>enable</Nullable>

New projects enable it by default. With it on:

  • string means "never null" as far as the compiler can tell.
  • string? means "may be null".
  • Dereferencing a string? without a check produces a warning.

The warnings are guidance, not runtime checks. A null can still reach a non-nullable variable through reflection, deserialisation or a method that lies, and the compiler cannot see those paths.

The warnings in practice

string? maybeName = Console.ReadLine();
// warning: possible null reference
// Console.WriteLine(maybeName.Length);
if (maybeName is not null)
{
Console.WriteLine(maybeName.Length);   // no warning
}
Console.WriteLine(maybeName?.Length ?? 0);  // no warning

Both fixes are honest: one checks, the other handles the absence. What you should not do is suppress the warning and hope.

The null-forgiving operator

string name = maybeName!;

The ! tells the compiler "trust me, this is not null". It generates no runtime check, so if you are wrong you get a NullReferenceException at that line.

Legitimate uses are narrow: after a check the compiler cannot follow, such as a validation method that throws. In that case, prefer an attribute or a helper that the compiler understands:

static void EnsureNotNull([NotNull] string? value)
{
if (value is null) throw new ArgumentNullException(nameof(value));
}

[NotNull] tells the compiler that the parameter is non-null after the call returns, so callers get no further warning.

Initialising non-nullable fields

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

A non-nullable property must be assigned before the constructor returns, or the compiler warns. Initialising to string.Empty and letting the constructor replace it is one option; requiring a value in the constructor is stricter and usually better.

For properties set by a framework, such as deserialisation, required expresses the contract:

public class Customer
{
public required string Name { get; init; }
}

Object creation without Name then fails to compile, which moves the error to the place that can fix it.

Nullable value types

int? count = null;
if (count.HasValue)
{
Console.WriteLine(count.Value);
}
int safe = count ?? 0;

int? is Nullable<int>, a struct with HasValue and Value. Reading Value when HasValue is false throws InvalidOperationException. The ?? operator and GetValueOrDefault avoid the check where a default is meaningful.

Nullable value types are the right representation for "a number that might be absent": a database column that can be null, a form field not filled in, a measurement not taken.

Where the compiler stops helping

  • Activator.CreateInstance and reflection.
  • JSON deserialisation into a non-nullable type, where a missing field leaves null.
  • Collections from external code that contain nulls despite the annotation.
  • Interop with C or unmanaged code.

At those boundaries, validate. A deserialised object is untrusted input, and the annotation is a claim by the JSON library, not a guarantee.

Designing with null

Prefer these, in order:

  1. Make the value impossible to be null: require it in the constructor.
  2. Make absence explicit: return string?, int? or a result type.
  3. Throw when absence is a programming error.
  4. Return an empty value rather than null for collections.

The worst option is a non-nullable declaration that sometimes returns null, because it makes every caller’s assumption wrong and the compiler silent.

Null and collections

List<string>? tags = null;
foreach (var tag in tags ?? Enumerable.Empty<string>())
{
Console.WriteLine(tag);
}

An empty sequence is better than null in almost every case: callers can loop, count and filter without a check. If a method returns a list, return an empty one rather than null.

Using ! to silence a warning in code you have not verified. The warning is the compiler telling you it cannot prove safety; suppressing it without a check converts a compile-time signal into a runtime crash.

Write a method that takes a nullable string and returns its trimmed length, treating null and whitespace as zero. Then write the caller so no warning is produced.

Show solution
static int LetterCount(string? text) { if (string.IsNullOrWhiteSpace(text)) { return 0; } return text.Trim().Length; } string? input = Console.ReadLine(); Console.WriteLine(LetterCount(input));

The guard returns before the dereference, so inside the method text is known non-null and no warning appears. The caller passes a nullable value without a check because the callee’s signature accepts one, which is the point of annotating it.

Recap

  • With nullable enabled, string? marks a possible null and the compiler warns on unchecked use.
  • ?., ?? and pattern checks handle absence; ! only silences the warning.
  • Annotations stop at reflection and deserialisation, so validate at those boundaries.

Module 2 covers conditions, switch expressions, loops, arrays and methods.

Does enabling nullable change runtime behaviour?
No. It adds compile-time warnings; the null still exists at runtime.
What does required do?
It forces an object initialiser to set the property, making the compiler enforce what the annotation promises.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.