Programming languages · Intermediate · 20 min
Catch null bugs at compile time with C# nullable reference types
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · .NET 10 LTS SDK (runtime 10.0.15, C# 14) · mcr.microsoft.com/dotnet/sdk:10.0
You will take a .NET 10 console app that crashes with a NullReferenceException, turn on nullable analysis with its warnings as errors, and fix every report with string?, required members, ?. and ??, pattern matching and [NotNullWhen] until the build is clean and the crash is gone.
On this page
NullReferenceException is one of the most common crashes in C# code, and it tends to arrive late: in production, on the one record nobody tested. The cause is that, by default in older projects, every reference type can secretly be null. A string might hold text, or it might hold nothing, and the compiler does not care which.
Nullable reference types change that. With them on, string means "never null" and string? means "might be null", and the compiler tracks which one each variable holds at every line. It then warns wherever you use a maybe-null value as if it were safe. The checks happen at compile time only; nothing changes in the program that runs. New projects from dotnet new have this on already. Older projects, and projects where someone switched it off, do not.
In this tutorial you start with a small customer-contact app that has the analysis off and crashes. You switch it on, make every nullable warning a build error, and work through the fixes one kind at a time. The running example sends order updates by email, or by SMS for customers who signed up with a phone number only. That second case is common in many markets, including much of Africa, where plenty of customers have a mobile number and no email address, and it is exactly the kind of gap that produces a null.
You need the .NET 10 SDK from the Hello World in C# tutorial. .NET 11 is also out, as a standard-term support release; nothing here was run on it, but the steps should work the same.
Step 1 · Build the app with null checks off
Create a console project in a throwaway folder:
mkdir -p ~/nullable-demo
cd ~/nullable-demo
dotnet new console -o NullDemo
cd NullDemoReplace the project file with one that has nullable analysis switched off. This is how many projects created before .NET 6 (late 2021), or upgraded from .NET Framework, look:
cd ~/nullable-demo/NullDemo
cat > NullDemo.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
</PropertyGroup>
</Project>
XMLNow add four source files. A customer has an ID, a name, and an email address and phone number that are each optional in real life, though nothing in the code says so:
cd ~/nullable-demo/NullDemo
cat > Customer.cs <<'CS'
namespace NullDemo;
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
CSA store keeps customers by ID. Find returns whatever the dictionary gives back, which is null for an ID it does not hold:
cd ~/nullable-demo/NullDemo
cat > CustomerStore.cs <<'CS'
namespace NullDemo;
public class CustomerStore
{
private readonly Dictionary<string, Customer> _byId = new();
public void Add(Customer customer) => _byId[customer.Id] = customer;
public Customer Find(string id)
{
_byId.TryGetValue(id, out var customer);
return customer;
}
}
CSThe notifier decides how to reach a customer. Its author assumed everyone has an email address:
cd ~/nullable-demo/NullDemo
cat > Notifier.cs <<'CS'
namespace NullDemo;
public static class Notifier
{
public static string Contact(Customer customer)
{
return "email " + customer.Email.ToLowerInvariant();
}
}
CSThe program adds two customers, one without an email address, and prints how each will be contacted:
cd ~/nullable-demo/NullDemo
cat > Program.cs <<'CS'
using NullDemo;
var store = new CustomerStore();
store.Add(new Customer { Id = "C-100", Name = "Amara Okafor", Email = "Amara@Example.com", Phone = "+234 803 555 0101" });
store.Add(new Customer { Id = "C-101", Name = "Kwame Mensah", Phone = "+233 24 555 0102" });
foreach (var id in new[] { "C-100", "C-101" })
{
Customer customer = store.Find(id);
Console.WriteLine($"{customer.Name}: {Notifier.Contact(customer)}");
}
CS
dotnet build
dotnet run || echo "dotnet run exited with status $?"Check it worked
dotnet build ends with a line like Build succeeded in 1.2s and shows no warning lines. The run prints Amara Okafor: email amara@example.com, then Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. with a stack trace that points at Notifier.cs:line 7, and the shell reports a non-zero status, such as 134. The compiler had everything it needed to spot this and said nothing, because nothing told it that Email can be missing.
Step 2 · Turn on nullable analysis and make its warnings errors
Two settings do the work. <Nullable>enable</Nullable> switches the analysis on for the whole project. <WarningsAsErrors>Nullable</WarningsAsErrors> turns every nullability warning into an error, so a build with a null problem fails instead of scrolling past. Nullable there is a shorthand the compiler understands for the whole family of nullable warnings, so you do not have to list them by number. Other warnings stay warnings.
cd ~/nullable-demo/NullDemo
cat > NullDemo.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<WarningsAsErrors>Nullable</WarningsAsErrors>
</PropertyGroup>
</Project>
XML
dotnet build || echo "dotnet build exited with status $?"Check it worked
The build fails. The errors are listed in file(line,column): error CODE: message form, grouped under the NullDemo project, and the last line reads something like Build failed with 5 error(s) in 1.4s. You see two kinds:
Customer.cs(5,19): error CS8618: Non-nullable property 'Id' must contain a non-null value when exiting constructor.and the same forName,EmailandPhone. A plainstringproperty now promises never to be null, but nothing sets these four when aCustomeris created.CustomerStore.cs(12,16): error CS8603: Possible null reference return.Findsays it returns aCustomer, butTryGetValueleavescustomernull when the ID is missing.
Notice what is not reported yet: the crash in Notifier.cs. The compiler believes the types you wrote, and Email is declared as never null. The fix starts with telling it the truth.
Step 3 · Say which values may be missing
Decide, field by field, what is allowed to be absent. Every customer has an ID and a name, so those stay string, and you mark them required: whoever creates a Customer must set them in the object initialiser, or the code does not compile. init instead of set means they can be set only while the object is being created. Email and phone may be missing, so they become string?:
cd ~/nullable-demo/NullDemo
cat > Customer.cs <<'CS'
namespace NullDemo;
public class Customer
{
public required string Id { get; init; }
public required string Name { get; init; }
public string? Email { get; init; }
public string? Phone { get; init; }
}
CSFind really can return nothing, so its return type becomes Customer?:
cd ~/nullable-demo/NullDemo
cat > CustomerStore.cs <<'CS'
namespace NullDemo;
public class CustomerStore
{
private readonly Dictionary<string, Customer> _byId = new();
public void Add(Customer customer) => _byId[customer.Id] = customer;
public Customer? Find(string id)
{
_byId.TryGetValue(id, out var customer);
return customer;
}
}
CS
dotnet build || echo "dotnet build exited with status $?"The ? on a reference type is only an annotation. At run time string? and string are the same type; the difference exists for the compiler alone.
Check it worked
The CS8618 and CS8603 errors are gone, and new ones point at the places that use these values:
Notifier.cs(7,27): error CS8602: Dereference of a possibly null reference.This is the line that crashed in the first step, now caught before the program runs.Program.cs(9,25): error CS8600: Converting null literal or possible null value to non-nullable type.The program stores the result ofFindin a plainCustomer.Program.cs(10,26): error CS8602follows from the same line.
To see required at work, try deleting Name = "Kwame Mensah", ` from `Program.cs and building: the compiler reports error CS9035: Required member 'Customer.Name' must be set in the object initializer or attribute constructor. Put it back before you go on.
Step 4 · Check for null with pattern matching
In Program.cs, keep the result of Find as a Customer? and test it before use. customer is not null is a pattern that checks for null without calling any != operator a class might define, so it means exactly what it says. Inside the if, the compiler knows customer is not null and stops warning. Add an ID that does not exist, so the missing case is exercised:
cd ~/nullable-demo/NullDemo
cat > Program.cs <<'CS'
using NullDemo;
var store = new CustomerStore();
store.Add(new Customer { Id = "C-100", Name = "Amara Okafor", Email = "Amara@Example.com", Phone = "+234 803 555 0101" });
store.Add(new Customer { Id = "C-101", Name = "Kwame Mensah", Phone = "+233 24 555 0102" });
foreach (var id in new[] { "C-100", "C-101", "C-999" })
{
Customer? customer = store.Find(id);
if (customer is not null)
{
Console.WriteLine($"{customer.Name}: {Notifier.Contact(customer)}");
}
else
{
Console.WriteLine($"{id}: no such customer");
}
}
CS
dotnet build || echo "dotnet build exited with status $?"Check it worked
The only error left is Notifier.cs(7,27): error CS8602: Dereference of a possibly null reference. Nothing is reported for Program.cs. The compiler followed the if and knows which branch has a real customer.
Step 5 · See why the null-forgiving ! is a last resort
There is a one-character way to silence the remaining error. Putting ! after an expression tells the compiler "trust me, this is not null". Try it, to see what it does and does not do:
cd ~/nullable-demo/NullDemo
cat > Notifier.cs <<'CS'
namespace NullDemo;
public static class Notifier
{
public static string Contact(Customer customer)
{
return "email " + customer.Email!.ToLowerInvariant();
}
}
CS
dotnet build
dotnet run || echo "dotnet run exited with status $?"Check it worked
The build succeeds with no errors, and the program crashes with the same NullReferenceException as in the first step. ! changes nothing at run time: it adds no check and throws no clearer error, it only switches the warning off. You are back to a crash the compiler could have caught.
Keep ! for the rare case where you know something the compiler cannot see, such as a value a framework is documented to set before your code runs, and add a comment saying why. If you find yourself writing it to make a build pass, the type is wrong or a check is missing.
Step 6 · Handle the missing value with ?. and ??
Write Contact so it copes with every customer. ?. is null-conditional access: customer.Email?.ToLowerInvariant() calls the method if Email has a value and gives null if it does not, so the result is a string?. ?? is null-coalescing: a ?? b gives a unless it is null, and then b. Together they cover the phone-only customer and the customer with no contact details at all:
cd ~/nullable-demo/NullDemo
cat > Notifier.cs <<'CS'
namespace NullDemo;
public static class Notifier
{
public static string Contact(Customer customer)
{
string? email = customer.Email?.ToLowerInvariant();
if (email is not null)
{
return $"email {email}";
}
return $"SMS {customer.Phone ?? "(no phone number)"}";
}
}
CS
dotnet build
dotnet runCheck it worked
The build ends with a line like Build succeeded in 1.1s and no error lines, and the program prints three lines and exits normally:
Amara Okafor: email amara@example.com
Kwame Mensah: SMS +233 24 555 0102
C-999: no such customerThe crash from the first step is fixed, and the fix was forced by the compiler rather than found by a customer.
Step 7 · Teach the compiler about a TryParse-style method
Many .NET APIs follow the TryParse shape: return true or false, and hand the result back through an out parameter. Dictionary.TryGetValue is one. Add your own TryFind to the store, and use it in Program.cs:
cd ~/nullable-demo/NullDemo
cat > CustomerStore.cs <<'CS'
namespace NullDemo;
public class CustomerStore
{
private readonly Dictionary<string, Customer> _byId = new();
public void Add(Customer customer) => _byId[customer.Id] = customer;
public Customer? Find(string id)
{
_byId.TryGetValue(id, out var customer);
return customer;
}
public bool TryFind(string id, out Customer? customer)
{
return _byId.TryGetValue(id, out customer);
}
}
CS
cat > Program.cs <<'CS'
using NullDemo;
var store = new CustomerStore();
store.Add(new Customer { Id = "C-100", Name = "Amara Okafor", Email = "Amara@Example.com", Phone = "+234 803 555 0101" });
store.Add(new Customer { Id = "C-101", Name = "Kwame Mensah", Phone = "+233 24 555 0102" });
foreach (var id in new[] { "C-100", "C-101", "C-999" })
{
if (store.TryFind(id, out var customer))
{
Console.WriteLine($"{customer.Name}: {Notifier.Contact(customer)}");
}
else
{
Console.WriteLine($"{id}: no such customer");
}
}
CS
dotnet build || echo "dotnet build exited with status $?"The build fails with Program.cs(11,30): error CS8602: Dereference of a possibly null reference. The out parameter is declared Customer?, and the compiler does not know that a true result means it was filled in.
Say so with the [NotNullWhen(true)] attribute from System.Diagnostics.CodeAnalysis. It means "when this method returns true, this parameter is not null". TryGetValue carries the mirror-image attribute, [MaybeNullWhen(false)], which is why it can pass its value straight through:
cd ~/nullable-demo/NullDemo
cat > CustomerStore.cs <<'CS'
using System.Diagnostics.CodeAnalysis;
namespace NullDemo;
public class CustomerStore
{
private readonly Dictionary<string, Customer> _byId = new();
public void Add(Customer customer) => _byId[customer.Id] = customer;
public Customer? Find(string id)
{
_byId.TryGetValue(id, out var customer);
return customer;
}
public bool TryFind(string id, [NotNullWhen(true)] out Customer? customer)
{
return _byId.TryGetValue(id, out customer);
}
}
CS
dotnet build
dotnet runCheck it worked
The build succeeds and the output is the same three lines as before. Inside if (store.TryFind(...)) the compiler now treats customer as a Customer, and in the else branch it would still warn if you used it. The attribute is a promise you make, so check that the method keeps it: here it does, because TryGetValue only returns true when it found an entry.
Step 8 · Turn it on gradually in a large codebase
On a real project with hundreds of files, enabling the analysis for everything at once can produce more errors than anyone wants to fix in one go. The #nullable directive sets the context for the rest of a single file, so you can move file by file. Add a legacy file that opts out:
cd ~/nullable-demo/NullDemo
cat > LegacyReport.cs <<'CS'
#nullable disable
namespace NullDemo;
public static class LegacyReport
{
public static string Header(Customer customer)
{
return customer.Email.ToUpperInvariant();
}
}
CS
dotnet buildThe build succeeds, even though Header has the same bug as the original notifier, because the compiler reports nothing in a disabled context. That is the trade-off: the file is unchecked until someone removes the directive. When you do, the error appears and you fix it like the others:
cd ~/nullable-demo/NullDemo
cat > LegacyReport.cs <<'CS'
namespace NullDemo;
public static class LegacyReport
{
public static string Header(Customer customer)
{
return customer.Email?.ToUpperInvariant() ?? customer.Name.ToUpperInvariant();
}
}
CS
dotnet build
dotnet runTwo ways to roll it out:
- Turn it on for the project, as here, and put
#nullable disableat the top of each file you have not fixed yet. Search for that line to see what is left, and remove it file by file. This keeps every new file checked from day one. - Leave
<Nullable>disable</Nullable>in the project and put#nullable enableat the top of each file you convert. This is gentler when almost nothing is ready, but new files start unchecked unless someone remembers the directive.
#nullable restore sets a file back to the project setting from that line on, which is useful for marking one block of code. Whichever you choose, keep <WarningsAsErrors>Nullable</WarningsAsErrors> so that converted files stay clean.
Check it worked
The final dotnet build ends with a line like Build succeeded in 1.1s and shows no warning or error lines, with nullable analysis on for every file and no ! anywhere in the code. dotnet run prints the same three lines as before.
When you are done, remove the demo:
cd ~
rm -rf ~/nullable-demoNext steps
- Query the customer list with filters, grouping and projections in query collections in C# with LINQ.
- Make slow network calls correct and cancellable in write async code in C# with Task, await and cancellation.
- See the same idea in another language in tighten an existing TypeScript project with strict checks, where
strictNullChecksplays the role of<Nullable>enable</Nullable>.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials