I recommend ??= all the time. It is one of my favorite C# operators for handling null.
So I was surprised when I turned on nullable reference types in an old project of mine, and the compiler flagged a line that used exactly that operator.
In this post, I will show you what one line in a .csproj found in a real .NET 5 project, why ??= was not enough, and how to turn nullable on in your own codebase without drowning in warnings.
TL;DR: I enabled nullable reference types in an old .NET 5 project with one line in the
.csproj. The compiler found 14 null risks without running a single line of code. The most surprising one used??=, an operator I usually recommend for null safety. Null-safe operators make your code shorter. The compiler is what makes it safe.
The Experiment
The project is a small Heroes API I built on .NET 5: heroes, their achievements, and a CQRS setup with MediatR. Nothing exotic. The kind of code most of us have somewhere.
I have been writing C# since 2016. This project was built with nullable turned off, so I expected some warnings. I did not expect a line using ??= to be one of them.
I made a copy of the project and added one line to the .csproj:
<PropertyGroup> <Nullable>enable</Nullable> </PropertyGroup> Then I built it. No code changes. No new packages.
| Warning | What it means | Count |
|---|---|---|
| CS8618 | A non-nullable property is never set | 10 |
| CS8603 | A method can return null | 3 |
| CS8601 | A possible null is assigned | 1 |
| Total | 14 |
Fourteen places where null could slip through, found by the compiler in seconds.
One honest note: my first count said 28. The default build output in newer SDKs can show the same warning twice. The checklist at the end of this post has a command that counts each warning once.
Here are the three warnings that taught me the most.
Warning 1: The Property Nobody Set (CS8618)
This one made up 10 of the 14 warnings.
CS8618 on a MediatR request: HeroName is declared as never null, but nothing guarantees it gets a value.
public class CreateHero : IRequest<int> { public string HeroName { get; set; } // CS8618 public DateTime DOB { get; set; } } With nullable enabled, string means "never null". But nothing in this class guarantees that HeroName gets a value. If a request arrives without it, HeroName stays null, and the first .Trim() or .Length on it throws a NullReferenceException.
The fix depends on what the property really means.
If it must always have a value, and you are on C# 11 or newer (.NET 7 and later), use required:
public required string HeroName { get; set; } On .NET 7 and newer, System.Text.Json also respects required, so a request without HeroName fails at deserialization instead of reaching your handler.
On older versions, like my .NET 5 project, initialize it and validate it:
public string HeroName { get; set; } = string.Empty; If the value is genuinely optional, say so:
public string? HeroName { get; set; } And one fix to avoid:
public string HeroName { get; set; } = null!; // silences the warning, fixes nothing Warning 2: The Method That Promises Too Much (CS8603)
CS8603: the handler promises a HeroInfo, but returns null when no hero is found.
public async Task<HeroInfo> Handle(GetHeroByID query, CancellationToken cancellationToken) { var hero = await _context.Heroes.Where(h => h.HeroID == query.Id).FirstOrDefaultAsync(); if (hero == null) { return null; // CS8603 } return hero; } The signature promises a HeroInfo. The code can return null. Every caller trusts that promise, and the one caller that forgets to check is where the NullReferenceException happens.
The fix is to make the promise honest:
public class GetHeroByID : IRequest<HeroInfo?> { public int Id { get; set; } public class GetHeroByIDHandler : IRequestHandler<GetHeroByID, HeroInfo?> { // constructor unchanged public async Task<HeroInfo?> Handle(GetHeroByID query, CancellationToken cancellationToken) { return await _context.Heroes .FirstOrDefaultAsync(h => h.HeroID == query.Id, cancellationToken); } } } Now the compiler makes every caller deal with the missing hero:
var hero = await Mediator.Send(new GetHeroByID { Id = id }); return hero is null ? NotFound() : Ok(hero); A small bonus: while fixing this, I noticed the original code never passed the cancellationToken to the query. Turning on nullable made me read the code again, and that is a benefit in itself.
Warning 3: Even ??= Didn't Save Me (CS8601)
This is the one that surprised me.
The line uses ??=, and the compiler still warns: the value being assigned can itself be null.
private IMediator _mediator; protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService(typeof(IMediator)) as IMediator; At first glance, this looks null-safe. That is exactly what ??= is for.
But ??= only helps if the value on the right side is not null itself. Here, two things can produce null:
-
GetServicereturns null ifIMediatoris not registered. -
as IMediatorreturns null if the cast fails.
So ??= can happily assign null, and a property that promises an IMediator hands back nothing. The crash would come later, at the first Mediator.Send(command), far away from the real cause.
Fix A: ask for a service that must exist.
using Microsoft.Extensions.DependencyInjection; private IMediator? _mediator; protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetRequiredService<IMediator>(); GetRequiredService throws a clear exception right here if IMediator is missing, instead of a vague NullReferenceException somewhere else. The field becomes IMediator?, because it really is null until first use.
Fix B: use constructor injection, which is what I would do today.
public class HeroesController : ControllerBase { private readonly IMediator _mediator; public HeroesController(IMediator mediator) { _mediator = mediator; } } The lesson: null-safe operators make null handling shorter. They do not make it correct. The compiler checks what the operators cannot.
The Null-Safety Toolbox
Here are the tools I reach for, and the one thing to watch with each.
?? for a default value
var name = user.Name ?? "Guest"; ?. for a chain that might break
var city = order?.Address?.City; Careful: ?. does not remove the null. It passes it along. If city is used later, the crash just moves. Pair it with ??:
var city = order?.Address?.City ?? "Unknown"; ??= to assign only when null
user.Name ??= "Guest"; As Warning 3 showed, make sure the right side cannot be null itself.
Guard your arguments
On .NET 6 and newer:
ArgumentNullException.ThrowIfNull(user); On older versions:
_context = context ?? throw new ArgumentNullException(nameof(context)); is not null for clear checks
if (hero is not null) { Console.WriteLine(hero.HeroName); } Unlike != null, the is not null pattern cannot be changed by a custom != operator on the type.
required for properties that must be set (C# 11)
public required string HeroName { get; set; } Null-conditional assignment (C# 14)
customer?.Order = GetCurrentOrder(); This assigns only when customer is not null. It shipped with .NET 10.
Use ! sparingly
var name = user.Name!; // "trust me, this is not null" The null-forgiving operator silences the compiler. Every ! is a promise the compiler can no longer check. Use it only when you know something the compiler cannot, and leave a comment saying why.
Turning It On Without Drowning in Warnings
A large old project can show hundreds of warnings at once. You do not have to fix them in one go.
Step 1: Start with one file. Add this at the top of a single file:
#nullable enable Step 2: Or see warnings without annotations. For the whole project, this mode shows nullable warnings without changing what your existing types mean:
<Nullable>warnings</Nullable> Step 3: Fix by warning type. Model classes usually produce most of the CS8618 warnings, so they are a quick, safe first batch.
Step 4: Lock in your progress. Once a project is clean, make new nullable warnings fail the build:
<WarningsAsErrors>nullable</WarningsAsErrors> For new projects, you do not need any of this. Project templates have enabled nullable by default since .NET 6.
Checklist: Find the Null Risks in Your Own Project
Step 1: Copy the project, so the original stays untouched.
Step 2: Enable nullable in the copy's .csproj with <Nullable>enable</Nullable>.
Step 3: Count the warnings, each one once. On Windows, in PowerShell, with the .NET 8 SDK or newer:
dotnet build YourProject.csproj --no-incremental -tl:off -clp:NoSummary 2>&1 | Select-String "warning CS86" | ForEach-Object { ($_.Line -split ' \[')[0] } | Sort-Object -Unique | Measure-Object On macOS or Linux, this gives a count per warning type:
dotnet build YourProject.csproj --no-incremental -tl:off -clp:NoSummary 2>&1 \ | grep "warning CS86" | sed 's/ \[.*//' | sort -u \ | grep -oE "CS86[0-9]{2}" | sort | uniq -c Step 4: Group them by type, using the Quick Reference below.
Step 5: Fix the closest-to-crash warnings first. CS8602 (dereferencing a possible null) and CS8603 (returning null) are usually closer to a real NullReferenceException than CS8618 on a model property.
Quick Reference
| Warning | What it means | Usual fix |
|---|---|---|
| CS8618 | A non-nullable property is never set | required, an initializer, or make it ? |
| CS8603 | A method can return null | Make the return type T? and handle null in the caller |
| CS8601 | A possible null is assigned | Fix the source, for example GetRequiredService |
| CS8602 | Dereferencing a possible null | Check first, use ?. with ??, or guard it |
| CS8604 | A possible null is passed as an argument | Check before passing, or make the parameter ? |
Key Takeaways
- One line in a
.csprojfound 14 null risks in a small, old project. - Most warnings (10 of 14) were properties and fields that are never set. The fix depends on whether the value is required, defaulted, or optional.
- A method that can return null should say so with
T?. Then the compiler protects every caller. -
??=is only as safe as the value on its right side. - You can turn nullable on gradually, one file or one warning type at a time.
Fourteen warnings in a small project was more than I expected.
To be honest, I have always worked with nullable turned off. I even recommended keeping it off to my teams. This experiment showed me what that choice can hide, but one experiment is not enough to change a habit built over years. My plan is to start my next real project with nullable enabled from day one, and see how it feels in daily work.
Over to You
Have you used nullable from day one in a real project? Was it worth the extra checks, or did you turn it off too? Tell me in the comments. I would really like to hear from people who have lived with it.
Thanks for reading! 🙏
If this helped, a reaction or a bookmark helps other C# developers find it too.
I publish practical .NET and C# posts every week. Follow me so you don't miss the next one.
📧 Hiring a .NET developer? Email me at contact@umerfarooqofficial.com
🌐 My portfolio and free .NET roadmap: https://umerfarooqofficial.com


