The value that isn't there
Look up a customer's phone number. Sometimes there is one; sometimes the customer never gave it; sometimes there is no such customer. For decades, languages in the C family expressed "nothing" with a null reference, and every variable of a reference type could secretly be null. Forget to check, call a method on it, and the program stops with a NullReferenceException, the most common crash in .NET history. Tony Hoare, who introduced null references in the ALGOL W language in 1965, later called the idea his "billion-dollar mistake".
C# 8 (2019) did something unusual for a mature language: it changed the meaning of existing syntax. With nullable reference types enabled, string means "a string, never null", and string? means "a string or null", and the compiler tracks which is which through your code and warns where a null could slip through. New projects have it on by default.
The second half of this lesson is about pattern matching: asking questions like "is this payment a card, and if so, is it international?" or "is this command the word add followed by at least one item?" in one readable expression. The two ideas meet often, because checking for null is the simplest pattern of all.
Nullable reference types
Definition— Nullable reference types
A compile-time analysis, switched on by setting the Nullable property to enable in a project file (it is on by default in new projects and in file-based apps). Reference types written without ? are treated as never null; with ? they may be null. The compiler tracks each variable's null state through assignments and checks, and warns when a maybe-null value is dereferenced or stored where null is not allowed. It changes nothing at run time.
Here is the classic mistake, and what the compiler says about it:
string? FindCity(int id) => id == 1 ? "Accra" : null;
string city = FindCity(2);
Console.WriteLine(city.Length);main.cs(2,15): warning CS8600: Converting null literal or possible null value to non-nullable type.
main.cs(3,19): warning CS8602: Dereference of a possibly null reference.These are warnings, not errors: the program still builds, and still crashes when run. Serious teams make them errors by adding one line to the project file, so a null bug cannot be merged:
<WarningsAsErrors>nullable</WarningsAsErrors>The operators for working with maybe-null values:
| Syntax | Meaning |
|---|---|
x?.Member | if x is null, the whole expression is null; otherwise access the member |
x ?? fallback | x if it is not null, otherwise fallback |
x ??= value | assign value to x only if x is null |
x is null, x is not null | null tests that cannot be fooled by a custom == operator |
x?.Member = value | C# 14: assign only if x is not null (the right side is not evaluated otherwise) |
x! | the null-forgiving operator: "trust me, it is not null"; silences the warning, checks nothing |
This program uses all but the last:
using System.Diagnostics.CodeAnalysis;
var book = new PhoneBook();
book.Add("Aiyana", "+1 555 0100");
book.Add("Bongani", null);
foreach (string name in new[] { "Aiyana", "Bongani", "Chen" })
{
string? phone = book.FindPhone(name);
// ?. stops at null; ?? supplies a fallback.
int digits = phone?.Count(char.IsAsciiDigit) ?? 0;
Console.WriteLine($"{name,-8} {phone ?? "(no phone)",-12} {digits} digits");
}
// The Try pattern with [NotNullWhen(true)]: after a true result, the compiler knows it's not null.
if (book.TryFind("Aiyana", out Contact? contact))
{
Console.WriteLine($"Found {contact.Name}"); // no warning: contact is known to be non-null here
}
// ??= assigns only when the left side is null.
string? nickname = null;
nickname ??= "friend";
nickname ??= "stranger";
Console.WriteLine($"Hello, {nickname}");
// C# 14: null-conditional assignment. The right side runs only if the target exists.
Contact? missing = null;
missing?.LastCalled = Stamp("missing");
Contact? present = book.FindContact("Aiyana");
present?.LastCalled = Stamp("present");
Console.WriteLine($"Aiyana last called: {present?.LastCalled:yyyy-MM-dd}");
static DateOnly Stamp(string who)
{
Console.WriteLine($" (computing a date for {who})");
return new DateOnly(2026, 11, 19);
}
sealed class Contact(string name, string? phone)
{
public string Name { get; } = name;
public string? Phone { get; } = phone;
public DateOnly? LastCalled { get; set; }
}
sealed class PhoneBook
{
private readonly Dictionary<string, Contact> _byName = [];
public void Add(string name, string? phone) => _byName[name] = new Contact(name, phone);
public Contact? FindContact(string name) => _byName.GetValueOrDefault(name);
public string? FindPhone(string name) => FindContact(name)?.Phone;
public bool TryFind(string name, [NotNullWhen(true)] out Contact? contact) =>
_byName.TryGetValue(name, out contact);
}It prints:
Aiyana +1 555 0100 8 digits
Bongani (no phone) 0 digits
Chen (no phone) 0 digits
Found Aiyana
Hello, friend
(computing a date for present)
Aiyana last called: 2026-11-19Points to notice:
- The types say what can be missing.
Nameisstring(every contact has one);Phoneisstring?(some do not). Anyone readingPhoneBooklearns this without reading its implementation. phone?.Count(char.IsAsciiDigit) ?? 0chains the two most useful operators: ifphoneis null,?.makes the count null, and??turns that into 0.FindContact(name)?.Phoneis null both when the contact is missing and when it has no phone; if a caller needs to tell those apart, the API must offer a way, which is whatTryFinddoes.[NotNullWhen(true)]is an attribute fromSystem.Diagnostics.CodeAnalysisthat tells the compiler: "when this method returns true, thisoutargument is not null". Without it,contact.Nameinside theifwould trigger a warning. The base class library is annotated the same way, which is whyif (dictionary.TryGetValue(key, out var v))needs no!.- Null-conditional assignment (C# 14) assigns only when the target exists, and, as the output shows, does not even evaluate the right-hand side when it does not:
Stamp("missing")never ran. DateOnly?is a different kind of?. On a value type,?creates a real wrapper type (the generic structNullable, here holding aDateOnly) withHasValueandValueproperties, which exists at run time. On a reference type,?is only an annotation for the compiler.
How the analysis follows your code
The compiler does not just look at declarations; it follows the flow of each method. After a check, it knows more:
void Greet(string? name)
{
if (name is null)
{
Console.WriteLine("Hello, whoever you are");
return;
}
// From here on, name is known to be non-null: no warning.
Console.WriteLine($"Hello, {name.ToUpperInvariant()}");
}
void Save(Order? order)
{
ArgumentNullException.ThrowIfNull(order); // throws if null, so...
Console.WriteLine(order.Id); // ...no warning here either
}Library methods carry attributes that teach the analysis what they guarantee. string.IsNullOrEmpty(s) returning false means s is not null; ArgumentNullException.ThrowIfNull never returns when its argument is null. Your own methods can carry the same attributes, as the phone book's TryFind shows.
The analysis also checks the other direction. Every constructor must leave non-nullable fields and properties with a value, or the compiler warns (CS8618). That warning is a good design prompt: either the value is truly required (take it as a constructor parameter or mark the property required), or it is genuinely optional (make it nullable and handle the missing case).
Using ! honestly
The null-forgiving operator ! exists for the cases where you know more than the compiler: a value set by a framework after construction, or a check the analysis cannot see. Each ! is a small promise with no enforcement, so treat it like a cast: rare, deliberate, and ideally explained by a comment. If your code has many, the types are probably wrong. A better fix is usually to make the value non-nullable (initialise it in the constructor, mark the property required) or to check it and throw a clear exception early.
Pattern matching
A pattern is a test on a value's type, shape or contents, optionally binding parts of it to new variables. Patterns appear after is (if (shape is Circle c)), in switch statements, and above all in switch expressions.
Pattern matching is one of the clearest examples of C# borrowing from functional languages. ML, Haskell and C#'s sibling F# have matched on the shape of data for decades. C# took the idea in steps: type patterns with is in C# 7 (2017), switch expressions, property and positional patterns in C# 8, relational and logical patterns in C# 9, extended property patterns in C# 10, and list patterns in C# 11. Each step was small, which is why older C# code often uses long chains of if and casts where modern code would use one switch expression. When you maintain such code, converting it is usually a safe and worthwhile refactoring, and editors offer to do it for you.
Consider a payment service in a market where customers pay by card, by mobile money wallet or in cash. The kinds of payment are a closed family, so they are modelled as records deriving from one abstract record, and the logic that varies by kind is written as switch expressions:
// A small closed family of payment kinds, modelled as records.
Payment[] payments =
[
new Card("Visa", 120.00m, IsInternational: false),
new Card("Mastercard", 80.00m, IsInternational: true),
new MobileMoney("M-Pesa", "+254 700 000 000", 2_500.00m),
new MobileMoney("bKash", "+880 1700 000000", 40.00m),
new Cash(15.50m),
];
foreach (Payment p in payments)
{
Console.WriteLine($"{Describe(p),-38} fee {Fee(p),6:F2}");
}
// Type patterns with property patterns, relational patterns and a when guard.
static decimal Fee(Payment payment) => payment switch
{
Cash => 0m,
Card { IsInternational: true } card => Math.Round(card.Amount * 0.03m, 2),
Card card => Math.Round(card.Amount * 0.015m, 2),
MobileMoney { Amount: <= 50m } => 0.10m,
MobileMoney m when m.Provider == "M-Pesa" => Math.Min(m.Amount * 0.01m, 15m),
MobileMoney m => m.Amount * 0.012m,
_ => throw new ArgumentException($"Unknown payment {payment}"),
};
// Positional patterns use the records' Deconstruct methods.
static string Describe(Payment payment) => payment switch
{
Card(var network, var amount, true) => $"{network} card (abroad), {amount}",
Card(var network, var amount, _) => $"{network} card, {amount}",
MobileMoney(var provider, _, var amount) => $"{provider} wallet, {amount}",
Cash(var amount) => $"cash, {amount}",
_ => "unknown",
};
abstract record Payment(decimal Amount);
sealed record Card(string Network, decimal Amount, bool IsInternational) : Payment(Amount);
sealed record MobileMoney(string Provider, string Phone, decimal Amount) : Payment(Amount);
sealed record Cash(decimal Amount) : Payment(Amount);It prints:
Visa card, 120.00 fee 1.80
Mastercard card (abroad), 80.00 fee 2.40
M-Pesa wallet, 2500.00 fee 15.00
bKash wallet, 40.00 fee 0.10
cash, 15.50 fee 0.00The kinds of pattern in use:
- Type pattern:
Cashmatches anyCash.Card cardmatches aCardand binds it to a new variablecardof typeCard. - Property pattern:
{ IsInternational: true }tests a property;{ Amount: <= 50m }nests a relational pattern inside it. Property patterns can nest as deep as the data:{ Address: { Country: "KE" } }, or since C# 10 simply{ Address.Country: "KE" }. whenguard: an arbitrary condition, for tests that are not patterns.- Positional pattern:
Card(var network, var amount, true)deconstructs a record into its parts, matching the third against the constanttrueand binding the others._is the discard, matching anything. - Order matters: arms are tried from the top, so the specific international-card arm must come before the general
Card cardarm. If you put them the other way round, the compiler reports that the second arm can never be reached.
Notice the final _ => throw arms. The compiler cannot know that Card, MobileMoney and Cash are the only kinds of Payment, since another file could add one, so without a catch-all arm it would warn that the switch is not exhaustive. That is a real gap in C# 14. C# 15 (with .NET 11, November 2026) closes it with closed hierarchies, a closed modifier that fixes the set of derived types so the compiler can check exhaustiveness, and with union types. Until your team moves to those versions, the catch-all throw is the honest way to say "this should never happen".
List patterns and logical patterns
List patterns (C# 11) match arrays and lists by their elements. [] is empty, [var x] has exactly one element, .. matches any number of elements (and .. var rest captures them). This makes small command interpreters pleasant to write. Logical patterns combine others with and, or and not, and parentheses group them:
// List patterns (C# 11) match on the shape of an array or list.
string[][] commands =
[
[],
["help"],
["add", "tea"],
["add", "rice", "beans", "salt"],
["remove", "3"],
["remove", "three"],
["export", "csv", "--quiet"],
];
foreach (string[] command in commands)
{
Console.WriteLine($"{string.Join(' ', command),-24} -> {Interpret(command)}");
}
static string Interpret(string[] words) => words switch
{
[] => "nothing to do",
["help"] => "showing help",
["add", var item] => $"adding {item}",
["add", var first, .. var rest] => $"adding {first} and {rest.Length} more",
["remove", var n] when int.TryParse(n, out int index) && index > 0 => $"removing item {index}",
["remove", _] => "remove needs a positive number",
[var verb, ..] => $"unknown command '{verb}'",
};
// Relational and logical patterns: and, or, not.
foreach (char c in "a7 Z?")
{
string kind = c switch
{
>= 'a' and <= 'z' or >= 'A' and <= 'Z' => "letter",
>= '0' and <= '9' => "digit",
' ' => "space",
_ => "other",
};
Console.WriteLine($"'{c}': {kind}");
}
object[] things = [42, "hello", 3.5, null!, new int[] { 1, 2 }];
foreach (object? o in things)
{
string text = o switch
{
null => "null",
int i and > 40 => $"a big int {i}",
int i => $"an int {i}",
string { Length: > 3 } s => $"a long string '{s}'",
not (int or string) and double d => $"a double {d}",
int[] { Length: 2 } pair => $"a pair of ints, sum {pair[0] + pair[1]}",
_ => "something else",
};
Console.WriteLine(text);
}It prints:
-> nothing to do
help -> showing help
add tea -> adding tea
add rice beans salt -> adding rice and 2 more
remove 3 -> removing item 3
remove three -> remove needs a positive number
export csv --quiet -> unknown command 'export'
'a': letter
'7': digit
' ': space
'Z': letter
'?': other
a big int 42
a long string 'hello'
a double 3.5
null
a pair of ints, sum 3Here the Interpret switch needs no catch-all: [] and [var verb, ..] together cover every array, and the compiler can see that. In the logical pattern for letters, and binds more tightly than or, just as && does with ||. And notice the one deliberate ! in the program: null! puts a null into an array declared as non-nullable object[], purely to show the null pattern. In real code, you would declare the array as object?[] instead.
How professionals use these features
- Turn nullable warnings into errors in every new project, and enable them file by file (
#nullable enableat the top of a file) when migrating an old codebase. Fix the types rather than sprinkling!. - Validate at the boundary, trust inside. Data from outside (JSON, a database, user input) may be null whatever the types say. Check it once where it enters, then pass non-nullable types inward.
- Prefer switch expressions to chains of
if/else ifwhen choosing a value by cases; they read as a table and the compiler checks for unreachable arms and missing cases. - Model "one of several kinds" as a record hierarchy and put the per-kind logic in switch expressions when the set of kinds is closed and the operations keep growing (fees, descriptions, validation, exports). Use virtual methods instead when the operations are fixed and new kinds keep arriving. This trade-off, sometimes called the expression problem, is one of the oldest in programming-language design.
- Keep patterns readable. A three-level nested property pattern with guards is clever once and confusing forever. Pull complex conditions into well-named methods or properties.
Common misconceptions
Misconception
"With nullable reference types on, my program can't throw NullReferenceException." The analysis is compile-time only and has holes: the ! operator, arrays of non-nullable references (which start filled with nulls), code compiled without annotations, and data created by reflection or deserialisation. It removes most null bugs, not all.
Misconception
"string? and int? are the same feature." int? is the run-time type Nullable<int>, a struct with HasValue. string? is an annotation; at run time it is just string. They look alike and behave alike in most code, but typeof, reflection and generic constraints can tell them apart.
Misconception
"x == null and x is null are the same." Usually, but a type can overload == to do anything, while is null always tests the reference itself. Modern style prefers is null and is not null.
Exercises
1. Nullable reference types and pattern matching
Warm-upComputationalWhat does this program print?
string? a = null;
string? b = "";
Console.WriteLine($"[{a?.Length}] [{b?.Length}] [{a ?? "x"}] [{b ?? "y"}]");
2. Nullable reference types and pattern matching
CoreHumanIn a project with <Nullable>enable</Nullable>, which statements are true? (Choose all that apply.)
3. Nullable reference types and pattern matching
CoreComputationalWhat does this program print?
static string Classify(int[] xs) => xs switch
{
[] => "empty",
[var only] => $"one: {only}",
[var first, .., var last] when first == last => "same ends",
[_, _] => "pair",
[.., > 100] => "ends big",
_ => "other",
};
Console.WriteLine(string.Join(" | ", new[] { Classify([4, 1, 4]), Classify([1, 2]), Classify([1, 2, 300]), Classify([7]) }));
4. Nullable reference types and pattern matching
CoreComputationalWhat does this program print?
object[] items = [5, -5, "5", 5L];
foreach (object item in items)
{
Console.Write(item switch
{
int n and > 0 => "P",
int => "N",
string => "S",
_ => "?",
});
}
Console.WriteLine();
5. Nullable reference types and pattern matching
CoreComputationalWhat does this program print?
int? count = null;
int total = (count ?? 10) + 1;
count ??= 3;
count ??= 4;
Console.WriteLine(total + count.Value);
6. Nullable reference types and pattern matching
CoreHumanWhat happens if, in the lesson's Fee method, the arm Card card => ... is moved above the arm Card { IsInternational: true } card => ...?
7. Nullable reference types and pattern matching
StretchHumanYou write public bool TryLoad(string id, out Order? order). Callers complain that after if (TryLoad(id, out var o)) the compiler warns when they use o.Total. What is the best fix?
Further reading and resources
- Nullable reference types · MicrosoftHow the compiler's null-state analysis works, and how to migrate older code.
- Attributes for null-state static analysis · MicrosoftNotNullWhen, MaybeNull, MemberNotNull and the rest.
- Patterns · MicrosoftThe reference for every kind of pattern.
- What's new in C# 15 · MicrosoftUnion types and closed hierarchies, which take this lesson's ideas further.