Nullable reference types
Nullable reference types let you tell the compiler which references may be null (string?) and which may not (string). The compiler then uses flow analysis to warn about possible NullReferenceExceptions at build time, before users see the crash.
25.1 Why is it used?
- With #nullable disable (the old default) string means "string or null" and the compiler knows nothing about null.
- So a method returning null gives zero warnings and the bug reaches production as a crash.
- With Nullable enabled, possible nulls become warnings (or errors) at compile time.
- File-based apps and new projects have it on by default.
25.2 The bug: zero warnings, crash
C#
#nullable disable var repo = new CustomerRepo();string name = repo.FindName(42);Console.WriteLine(name.ToUpper()); class CustomerRepo{ Dictionary<int, string> names = new() { [1] = "Asha", [2] = "Ravi" }; public string FindName(int id) => names.GetValueOrDefault(id);}Output
$ dotnet run Bug.csUnhandled exception.System.NullReferenceException: Object reference not set to an instance of an object. at Program.<Main>$(String[] args) in Bug.cs:line 5- GetValueOrDefault returns null for the missing id 42, but FindName claims to return string.
- With nullable on (same code, no #nullable disable) you get warning CS8603, but a warning alone still lets it run and crash.
Output
$ dotnet run Warn.csWarn.cs(10,12): warning CS8603: Possible null reference return.Unhandled exception.System.NullReferenceException: Object reference not set to an instance of an object. in Warn.cs:line 325.3 Project setting: Nullable + WarningsAsErrors
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>Output
$ dotnet buildBuild FAILED.Program.cs(10,12): error CS8603: Possible null reference return. 0 Warning(s) 1 Error(s)- <Nullable>enable</Nullable> turns on null checks for the whole project.
- <WarningsAsErrors>Nullable</WarningsAsErrors> makes every null warning a build error, so the bug cannot be deployed.
- In a big old project, migrate file by file with the #nullable enable directive.
25.4 Fix: string? + null check
C#
var repo = new CustomerRepo();string? name = repo.FindName(42);if (name is null) Console.WriteLine("Customer not found");else Console.WriteLine(name.ToUpper()); class CustomerRepo{ Dictionary<int, string> names = new() { [1] = "Asha", [2] = "Ravi" }; public string? FindName(int id) => names.GetValueOrDefault(id);}Output
$ dotnet run Fix.csCustomer not found- string? honestly says the method can return null.
- Without the null check, name.ToUpper() gives CS8602; after the check, name is not-null in the else branch.
- Step 1
1.Annotation: string cannot be null, string? can
- Step 2
2.Flow analysis tracks each variable's state on every line: not-null or maybe-null
- Step 3
3.Member call on maybe-null, or assigning it to non-nullable: warning
- Step 4
4.Null check (is null, ??, guard) changes the state to not-null
All at compile time, nothing at run time
| Warning | Meaning |
|---|---|
| CS8600 | Converting null literal or possible null value to non-nullable type |
| CS8602 | Dereference of a possibly null reference |
| CS8603 | Possible null reference return |
| CS8604 | Possible null reference argument |
25.5 Guard clauses: check public input
- Compiler warnings exist only at compile time; old callers or JSON data can still pass null.
- ArgumentException.ThrowIfNullOrWhiteSpace rejects null, empty and whitespace strings.
- ArgumentNullException.ThrowIfNull rejects null.
C#
var sms = new SmsSender();sms.Send("98100 12345", "Order shipped");sms.Send(" ", "Order shipped"); class SmsSender{ public void Send(string phone, string text) { ArgumentException .ThrowIfNullOrWhiteSpace(phone); ArgumentNullException.ThrowIfNull(text); Console.WriteLine($"SMS {phone}: {text}"); }}Output
$ dotnet run Guard.csSMS 98100 12345: Order shippedUnhandled exception. System.ArgumentException: The value cannot be an empty string or composed entirely of whitespace. (Parameter 'phone') at SmsSender.Send(String phone, String text) in Guard.cs:line 925.6 Try methods and [NotNullWhen(true)]
- A Try method returns bool and gives the result in out string? name (null when it returns false).
- Without help, the compiler cannot link the bool to the out value, so CS8602 appears even inside if (true).
Output
$ dotnet run Try.csTry.cs(3,23): warning CS8602: Dereference of a possibly null reference.ASHAC#
using System.Diagnostics.CodeAnalysis; var repo = new CustomerRepo();if (repo.TryFindName(1, out var name)) Console.WriteLine(name.ToUpper()); class CustomerRepo{ Dictionary<int, string> names = new() { [1] = "Asha", [2] = "Ravi" }; public bool TryFindName(int id, [NotNullWhen(true)] out string? name) => names.TryGetValue(id, out name);}Output
$ dotnet run Try.csASHA- Same family: MaybeNullWhen, NotNull, MemberNotNull give the compiler similar extra information.
- string.IsNullOrEmpty already has [NotNullWhen(false)], so after if (string.IsNullOrEmpty(city)) return; reading city.Length gives no warning (prints 4 with CITY=Pune).
25.7 Comparison: ways to deal with a maybe-null value
| Approach | Example | Effect |
|---|---|---|
| Null check | if (name is null) ... else ... | Safe, compiler state becomes not-null |
| ?? throw | repo.FindName(42) ?? throw new KeyNotFoundException(...) | Clear exception with a proper message |
| Guard clause | ArgumentNullException.ThrowIfNull(text) | Run-time check on public input |
| Null-forgiving ! | name!.ToUpper() | Only hides the warning; same crash if null |
25.8 Common mistakes
- Using ! (null-forgiving operator) just to silence a warning: the value is still null and the same NullReferenceException comes at run time.
- Use ! only when you truly know more than the compiler.
- Myth: Nullable on means no nulls at run time. string and string? are the same type in compiled code; these are compile-time annotations only.
- int? is different: it is a real Nullable<int> struct.
C#
string name = repo.FindName(42) ?? throw new KeyNotFoundException( "Customer 42 not found");Console.WriteLine(name.ToUpper()); // KeyNotFoundException:// Customer 42 not found25.9 Rules
- Nullable enable in every project; if possible WarningsAsErrors for Nullable.
- Add ? only where a value can really be missing.
- Guard clauses in public methods.
- NotNullWhen on Try methods.
- ! is the last option.
25.10 Interview tips
- With Nullable enabled the compiler distinguishes string from string? and uses flow analysis to warn about possible nulls.
- It is compile time only, so public APIs still need guard clauses like ThrowIfNull.
- NotNullWhen(true) on Try methods links the bool result to the out value.
- The null-forgiving ! hides the warning, not the null; use it rarely.
- int? (Nullable<T> struct) is a real type; string? is just an annotation.