C# · Lesson 5
Pattern matching & nullable references
Switch expressions and the full pattern toolbox (type, property, positional, relational, list), nullable reference types and flow analysis, Try-style APIs, and modelling a domain with records and patterns, compared with F# unions and TypeScript discriminated unions.
In short
x is T name: test the type and name it- Property patterns turn rules into a table
- Unions in C# 12: abstract record, sealed cases, a
_arm string?may be null,stringmay not?.,??and??=work as in TypeScript- Don't silence warnings with
!: handle the null
Modern C# reads a lot like TypeScript and F#. You write switch expressions instead of long if chains,
small records instead of classes with ten mutable properties, and the compiler tracks null for you. In a
.NET service you'll see this everywhere: turning a domain result into an HTTP response, deciding what to do
with a queue message based on its type and properties, parsing configuration. Every pull request also gets
nullable warnings ("CS8602: Dereference of a possibly null reference"). You need to fix those properly, not
silence them.
This topic has two halves that meet in the middle:
- Patterns answer "what shape is this value?": its type, its properties, its elements.
- Nullable reference types answer "can this be null here?", using the same checks (
is null,is not null,is { }) as evidence.
Every C# block below has a ▶ Try button. Predict the output, then run it.
is: test and name in one step
object payload = 42m;
if (payload is decimal amount && amount > 0)
Console.WriteLine($"positive amount {amount}");
if (payload is not string)
Console.WriteLine("not a string");
string? note = null;
Console.WriteLine(note is null); // True
Console.WriteLine(note is not null); // False
Console.WriteLine(note is string); // False: a type pattern never matches null
x is T namechecks the type and declaresname, already converted toT. It's likeinstanceofnarrowing in TypeScript, except you get a new variable instead of the same one narrowed.is nullandis not nullalways do a real null check.== nullcalls the type's==operator if it overloads one, so preferis null.- Type patterns never match
null. That's whyif (x is Customer c)is also a null check.
The TypeScript version narrows the same variable:
const payload: unknown = 42;
if (typeof payload === 'number' && payload > 0) console.log(`positive amount ${payload}`);
Switch expressions
foreach (var code in new[] { 200, 204, 404, 503, 302 })
Console.WriteLine($"{code}: {Describe(code)}");
static string Describe(int statusCode) => statusCode switch
{
200 => "OK",
404 => "Not found",
>= 200 and < 300 => "Success",
>= 500 => "Server error",
_ => "Something else",
};
- A switch expression produces a value. Each arm is
pattern => value, arms are separated by commas, and a trailing comma is fine. - Arms are tried top to bottom and the first match wins, so specific arms go first. If an arm can never
be reached because earlier arms already cover it, that's a compile error (CS8510). Try it: add
>= 400 and < 500 => "Client error",above the404arm. _is the discard: it matches anything.- If no arm matches at runtime you get a
SwitchExpressionException. The compiler warns (CS8509) when it can see inputs that no arm handles. - A
whenclause adds any boolean condition:int n when n % 2 == 0 => "even".
The older switch statement (case ...: break;) accepts the same patterns. Use it when each branch runs
statements instead of producing a value.
The pattern toolbox
| Pattern | Example | Matches when |
|---|---|---|
| constant | 404, "paid", null | the value equals the constant |
| type | Card c, decimal | the value has that type (never null) |
| relational | > 100, <= 0m | the comparison holds (numbers, char, enums) |
| logical | >= 200 and < 300, "NL" or "BE", not null | combines patterns |
| property | { Status: "paid", Total: > 100m } | not null, and every listed property matches |
| extended property | { Customer.Country: "NL" } | shorthand for { Customer: { Country: "NL" } } |
| positional | Point(0, var y), (0, 0) | deconstructs (records, tuples) and matches each part |
var | var x | always, including null, and names the value |
| discard | _ | always |
| list | [], [var first, ..], [_, _, .. var rest] | arrays, lists and strings, element by element |
Property patterns are where this gets useful for business rules:
var orders = new Order[]
{
new("A-1", 250m, new Customer("Ann", "NL", IsVip: false)),
new("A-2", 40m, new Customer("Bo", "DE", IsVip: true)),
new("A-3", 40m, new Customer("Cy", "BE", IsVip: false)),
new("A-4", 120m, new Customer("Di", "US", IsVip: false)),
};
foreach (var order in orders)
{
var shipping = order switch
{
{ Total: >= 200m } => 0m,
{ Customer.IsVip: true } => 0m,
{ Customer.Country: "NL" or "BE" or "DE" } => 4.95m,
_ => 14.95m,
};
Console.WriteLine($"{order.Id}: shipping {shipping}");
}
record Customer(string Name, string Country, bool IsVip);
record Order(string Id, decimal Total, Customer Customer);
A property pattern never matches null, and { Customer.IsVip: true } checks that Customer isn't null
before it reads IsVip, so patterns can't throw a NullReferenceException. The empty property pattern
{ } means "anything that isn't null", and x is { } y both tests for null and names the value.
Positional and tuple patterns
Positional records get a Deconstruct method, so you can match their parts by position. Switching on a
tuple matches several values together, which is the neatest way to write a decision table or a state
machine:
Console.WriteLine(Quadrant(new Point(0, 0)));
Console.WriteLine(Quadrant(new Point(3, 4)));
Console.WriteLine(Quadrant(new Point(0, -2)));
Console.WriteLine(NextLight("green", emergency: false));
Console.WriteLine(NextLight("green", emergency: true));
static string Quadrant(Point p) => p switch
{
(0, 0) => "origin",
(> 0, > 0) => "top right",
(< 0, > 0) => "top left",
(_, 0) or (0, _) => "on an axis",
_ => "bottom half",
};
static string NextLight(string light, bool emergency) => (light, emergency) switch
{
(_, true) => "red",
("green", _) => "amber",
("amber", _) => "red",
("red", _) => "green",
_ => throw new ArgumentOutOfRangeException(nameof(light), light, "Unknown light"),
};
record Point(int X, int Y);
List patterns
List patterns (C# 11) match arrays, lists and strings element by element. .. matches any number of
elements (at most once per pattern), and .. var rest captures them when the type supports slicing, as
arrays and strings do.
foreach (var path in new[] { "/", "/orders", "/orders/42", "/orders/42/lines/1", "/admin/users/7" })
Console.WriteLine($"{path} -> {Route(path)}");
static string Route(string path) => path.Split('/', StringSplitOptions.RemoveEmptyEntries) switch
{
[] => "home",
["orders"] => "list orders",
["orders", var id] => $"order {id}",
["orders", var id, "lines", ..] => $"lines of order {id}",
[var first, .. var rest] => $"unknown '{first}' plus {rest.Length} more segment(s)",
};
Modelling with records and patterns
Here's the same domain type in all three languages: a payment that was approved, declined, or needs the customer to do something.
type PaymentResult =
| { kind: 'approved'; transactionId: string }
| { kind: 'declined'; reason: string }
| { kind: 'needsAction'; redirectUrl: string };
function message(r: PaymentResult): string {
switch (r.kind) {
case 'approved': return `Paid (${r.transactionId})`;
case 'declined': return `Declined: ${r.reason}`;
case 'needsAction': return `Continue at ${r.redirectUrl}`;
}
}
console.log(message({ kind: 'declined', reason: 'insufficient funds' }));
type PaymentResult =
| Approved of transactionId: string
| Declined of reason: string
| NeedsAction of redirectUrl: string
let message result =
match result with
| Approved id -> $"Paid ({id})"
| Declined reason -> $"Declined: {reason}"
| NeedsAction url -> $"Continue at {url}"
printfn "%s" (message (Declined "insufficient funds"))
C# has no union types (C# 14 included), so the idiom is an abstract base record with sealed derived records:
using System.Diagnostics;
PaymentResult result = new Declined("insufficient funds");
Console.WriteLine(Message(result));
Console.WriteLine(new Approved("tx-1") == new Approved("tx-1")); // records compare by value
static string Message(PaymentResult result) => result switch
{
Approved a => $"Paid ({a.TransactionId})",
Declined(var reason) => $"Declined: {reason}",
NeedsAction { RedirectUrl: var url } => $"Continue at {url}",
_ => throw new UnreachableException(),
};
abstract record PaymentResult;
sealed record Approved(string TransactionId) : PaymentResult;
sealed record Declined(string Reason) : PaymentResult;
sealed record NeedsAction(string RedirectUrl) : PaymentResult;
The three arms show three ways to get at the data: a type pattern with a variable, a positional pattern, and a property pattern. Pick whichever reads best.
Why the _ arm? F# and TypeScript know the full list of cases: F# warns about a missing one (FS0025,
which many teams turn into an error), and TypeScript catches it through the return type or a never check.
The C# compiler doesn't treat the hierarchy as closed, because another class could derive from
PaymentResult, so without _ you get warning CS8509. And if a teammate adds a fourth record, your switch
still compiles: the new case falls through to _ at runtime. Throwing UnreachableException there makes a
missed case fail loudly. Tests that cover every case are your real safety net.
Records also give you value equality, a readable ToString(), deconstruction and non-destructive updates
with with: order with { Status = "paid" }. One catch: a record compares its members with Equals, and
arrays and List<T> compare by reference. Two records holding equal-looking arrays are not equal.
Nullable reference types
With <Nullable>enable</Nullable> (the default for new projects, and on in this lab):
stringmeans "never null" andstring?means "might be null". The compiler tracks every variable and warns when you might dereference null or store null where it doesn't belong.- It's compile-time only. At runtime
string?andstringare the sameSystem.String, with no checks added. The diagnostics are warnings, unless the project turns them into errors (<WarningsAsErrors>nullable</WarningsAsErrors>, which many teams do). - Value types are different.
int?isNullable<int>, a real struct withHasValueandValue.
string? middle = FindMiddleName("Grace");
Console.WriteLine(middle?.Length); // ?. gives null instead of throwing (prints an empty line)
Console.WriteLine(middle ?? "(none)"); // ?? supplies a fallback
middle ??= "unknown"; // assigns only when it's null
Console.WriteLine(middle.Length); // no warning: the compiler knows middle isn't null now
int? quantity = null;
Console.WriteLine(quantity.HasValue); // False
Console.WriteLine(quantity.GetValueOrDefault()); // 0
static string? FindMiddleName(string firstName) => firstName == "Ada" ? "King" : null;
Flow analysis
The compiler follows your checks, much like TypeScript's narrowing under strictNullChecks:
Console.WriteLine(NameLength(null));
Console.WriteLine(Shout("hi"));
static int NameLength(string? name)
{
if (name is null) return 0;
return name.Length; // fine: null was handled above
}
static string Shout(string? text)
{
if (string.IsNullOrEmpty(text)) return "";
return text.ToUpperInvariant(); // fine: IsNullOrEmpty is annotated with [NotNullWhen(false)]
}
It can't follow everything. A check inside another method only counts if that method is annotated (more on
that below). A field or property can change between the check and the use, so copy it into a local
first. And dictionary[key] assumes the key exists.
| Warning | Meaning | Usual fix |
|---|---|---|
| CS8600 | Converting null (or a maybe-null value) to a non-nullable type | make the variable T?, or handle null first |
| CS8602 | Dereference of a possibly null reference | check for null, or use ?. / ?? |
| CS8603 | Possible null reference return | return T?, or don't return null |
| CS8604 | Possible null reference argument | handle null before the call |
| CS8618 | Non-nullable property is uninitialized when the constructor exits | constructor parameter, required, or a default value |
! silences the compiler, not the bug
name!.Length means "trust me, this isn't null". It does nothing at runtime: if you're wrong you get the
same NullReferenceException, just without the warning that predicted it. Use it only when you really know
more than the compiler, for example right after a check the compiler can't see. One common, accepted use is
= null!; on properties that a framework fills in, like EF Core's DbSet<T> properties.
required members
required (C# 11) makes callers set a property in the object initializer. It's the clean fix for CS8618 on
options and DTO classes that have no constructor:
var options = new EmailOptions { Host = "smtp.example.com", From = "noreply@example.com" };
Console.WriteLine($"{options.Host}:{options.Port}, reply-to {options.ReplyTo ?? "(none)"}");
class EmailOptions
{
public required string Host { get; init; }
public required string From { get; init; }
public int Port { get; init; } = 587;
public string? ReplyTo { get; init; }
}
The Try pattern and nullable attributes
.NET's convention for "this may fail, and that's normal" is a Try method: return a bool and put the
result in an out parameter. You'll use int.TryParse, Guid.TryParse, Dictionary.TryGetValue and
Enum.TryParse constantly.
if (int.TryParse("42", out var n)) Console.WriteLine(n + 1);
var prices = new Dictionary<string, decimal> { ["SKU-1"] = 9.99m };
Console.WriteLine(prices.TryGetValue("SKU-2", out var price) ? price.ToString() : "no price");
When you write your own Try method with a reference type, add [NotNullWhen(true)]. It tells the compiler
"when this returns true, the out value isn't null", so callers get flow analysis for free:
using System.Diagnostics.CodeAnalysis;
var customers = new CustomerDirectory();
if (customers.TryFind("c-1", out var customer))
Console.WriteLine(customer.Name); // no warning: true means not null
if (!customers.TryFind("c-9", out var missing))
Console.WriteLine($"not found, missing is {(missing is null ? "null" : "set")}");
class CustomerDirectory
{
private readonly Dictionary<string, Customer> _byId = new() { ["c-1"] = new Customer("c-1", "Ada") };
public bool TryFind(string id, [NotNullWhen(true)] out Customer? customer) =>
_byId.TryGetValue(id, out customer);
}
record Customer(string Id, string Name);
The other attributes you'll meet in the framework's own signatures:
[MaybeNullWhen(false)] out T value: the generic version, used byDictionary<TKey, TValue>.TryGetValue.[NotNullWhen(false)]on a parameter:string.IsNullOrEmpty(value)returning false provesvalueisn't null.[NotNull]on a parameter: after the call it's not null (the method throws otherwise), as inArgumentNullException.ThrowIfNull.[MemberNotNull(nameof(_field))]: this helper method sets the field, so the constructor that calls it is fine.
Which style when?
| Style | Use it when |
|---|---|
bool TryX(..., out T value) | failure is normal and cheap to report: parsing input, cache lookups, hot paths |
return T? | "not found" is the only way it can fail: FirstOrDefault, FindAsync |
| throw | the caller can't sensibly carry on: a bug, a broken invariant, missing configuration |
| result type | several expected failures the caller must handle differently (see the errors topic) |
F# usually turns a Try method into an Option, matching on the returned tuple:
let tryParseInt (s: string) =
match System.Int32.TryParse s with
| true, n -> Some n
| false, _ -> None
printfn "%A %A" (tryParseInt "42") (tryParseInt "forty-two")
Generics: T? doesn't always mean nullable
In a generic method without a constraint, T? means "T, or its default". For reference types that's
null, but for value types it's just T, with 0, false or DateTime.MinValue as the default. That's why
FirstOrDefault on an empty int[] returns 0, not null:
int[] ids = [];
Console.WriteLine(ids.FirstOrDefault()); // 0
Console.WriteLine(ids.FirstOrDefault(-1)); // -1: the overload that takes a default
int? first = ids.Select(id => (int?)id).FirstOrDefault();
Console.WriteLine(first is null); // True: now "missing" and 0 are different
If 0 is a real value in your data (a quantity, a balance), don't use FirstOrDefault to mean "not found".
Common mistakes
- A general arm before a specific one. If the specific arm becomes unreachable the compiler stops you
(CS8510), but with
whenclauses it can't tell, and the general arm silently wins. !to make a warning go away. The warning described a real path where the value is null. Handle it, or change the type to say it can't be null.- Trusting annotations at runtime. A public method that takes
string namecan still receivenullfrom a caller with nullable disabled, a!, or reflection. Guard public entry points withArgumentNullException.ThrowIfNull(name). - Trusting JSON.
System.Text.Jsonleaves a non-nullablestringpropertynullwhen the field is missing from the payload, unless the property isrequiredor you turn on stricter options. Validate input. is var xas a null check.varmatches null. Useis { } xoris not null.- No
_arm on a record hierarchy. You get CS8509, and an unhandled case throwsSwitchExpressionExceptionat runtime.
In a real codebase
Side note
Mapping a domain result to HTTP in an ASP.NET Core minimal API is a switch expression:
// ASP.NET Core minimal API (not runnable here)
app.MapPost("/payments", async (PaymentRequest request, IPaymentService payments, CancellationToken ct) =>
{
var result = await payments.ChargeAsync(request, ct);
return result switch
{
Approved a => Results.Ok(new { a.TransactionId }),
Declined { Reason: "insufficient_funds" } => Results.Problem(statusCode: 402, title: "Insufficient funds"),
Declined d => Results.Problem(statusCode: 422, title: d.Reason),
NeedsAction n => Results.Accepted(n.RedirectUrl),
_ => throw new UnreachableException(),
};
});
- A message-queue consumer often dispatches on a message type attribute:
message.Type switch { "OrderPlaced" => ..., "OrderCancelled" => ..., _ => deadLetter }. - EF Core reads your annotations: a
string?property becomes a nullable column, andstringbecomesNOT NULL. - Expect
<Nullable>enable</Nullable>in every project file, often with<TreatWarningsAsErrors>true</TreatWarningsAsErrors>. In a codebase like that, a nullable warning fails the build.
Cheat sheet
| C# | TypeScript | F# | |
|---|---|---|---|
| union type | abstract record + sealed records | { kind: 'a' } | { kind: 'b' } | type T = A of ... | B of ... |
| match on it | x switch { A a => ..., _ => ... } | switch (x.kind) | match x with |
| missing case | warning, _ arm, runtime exception | error with a never check | warning (often treated as an error) |
| maybe a value | T? with flow analysis | T | undefined with strictNullChecks | Option<'T> |
| fallback | a ?? b | a ?? b | Option.defaultValue b a |
| safe access | a?.B | a?.b | a |> Option.map (fun x -> x.B) |
| parse or fail | int.TryParse(s, out var n) | Number(s) and an isNaN check | match Int32.TryParse s with | true, n -> ... |
The exercises
- HTTP status categories: a switch expression with constants, relational patterns and
or. - Config lookup with Try methods:
[NotNullWhen(true)],outparameters andint.TryParse. - Discount rules: property and extended property patterns over an order, with
decimalmoney. - Route matching with list patterns: turn URL segments into typed route records.
- Bank account decider: event sourcing with records, tuple patterns and a nullable state.
- Filter simplifier: recursive positional patterns that rewrite a query filter tree.
Practise this lesson
In the app: a short video, 6 exercises checked by real tests and a 10-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.
Open in the app