Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 182 ยท Pattern Matching and Modern C#

Modeling with Records and Pattern Matching

Model data with sealed record hierarchies and pattern matching in C#. Build discriminated-union style types, state machines and an expression evaluator, plus a look at the union proposal.

Some data is naturally "one of several shapes". A payment is a card payment or a bank transfer or cash. A parse result is a success with a value or a failure with an error message. A shape is a circle or a rectangle or a triangle. Functional languages express this with sum types or discriminated unions. C# has had no dedicated syntax for them, but a small pattern built from abstract records, sealed records and switch expressions gives you most of the benefit today.

This lesson builds the pattern step by step and then applies it to three realistic problems: a state machine, an arithmetic expression evaluator and a typed result. It assumes you know records, inheritance and the pattern syntax from Pattern Matching in Depth.

The idea: closed families of data

A discriminated union has two properties:

  1. A value is exactly one of a fixed list of cases.
  2. Each case carries its own data, different from the other cases.

In C#, the encoding is:

  • an abstract record (or abstract record class) as the base type, with a private protected constructor so that nobody outside the declaration can add new cases;
  • one sealed record per case, nested inside the base or declared next to it;
  • a switch expression that lists the cases.
C# A union of shapes as sealed records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The private protected constructor means only code inside Shape (including its nested types) can derive from it, so the list of cases is closed at the source level. Marking each case sealed prevents further subclasses. The compiler still cannot prove the list is complete, which is why each switch ends in a throwing _ arm. Adding a Square case later means searching for every switch on Shape, and tests are your safety net.

Notice what the model gives you for free: each case prints itself (Circle { Radius = 1.5 }), compares by value and deconstructs in a pattern.

Operations outside the types

In the example, Area and Perimeter are functions about shapes, not methods of shapes. This is the key trade-off from the previous lesson. A virtual method is easy to extend with new types; a switch is easy to extend with new operations. Data modeled as a closed family, where the cases rarely change but you keep adding operations (draw, serialize, validate, optimize), is a perfect fit for the union style.

A state machine

State machines describe things that move through stages: orders, connections, documents under review. Each state may carry different data. Records make states explicit and a (state, event) tuple switch lists every legal transition in one table.

C# An order state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last event, Cancel, arrives after the order was already delivered, and the final arm catches every illegal combination (the output ends with Failed { Previous = Delivered { Id = 17 }, Message = Cancel is not allowed in state Delivered }). Instead of throwing, it produces a Failed state that remembers the previous state, so the caller can decide what to do. Three design benefits show up:

  • Illegal data is not representable. A Created order has no tracking number; a Shipped order must have one. There is no nullable Tracking field that is sometimes valid.
  • All transitions are in one table, readable by someone who does not know C# well.
  • States are immutable. A transition creates a new state record rather than mutating the old one, which makes history, undo and testing straightforward.

Compare this with the typical "enum plus a bag of nullable fields" design, which allows a Delivered order with no tracking number and requires scattered if checks to stay consistent.

An expression evaluator

Interpreters and compilers use this style constantly, because syntax trees are unions of node types. Here is an arithmetic evaluator with variables.

C# Evaluating and simplifying an expression tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Simplify is where pattern matching shines. The rule "adding zero changes nothing" is a literal translation: (Expr.Num(0), var x) => x. Nested positional patterns look inside the tree, matching a Num whose value is the constant 0. The same rules written with if statements, casts and property reads would be several times longer. Because every node is an immutable record, Simplify returns new trees and never changes its input, so sharing subtrees is safe.

A typed result instead of exceptions

Parsing, validation and I/O produce expected failures. Rather than throwing, a method can return a Result that is either a success holding a value or a failure holding an error, and callers are forced by the type to look at both. This builds on the TryParse thinking from Validating Input and Defensive Programming. Generic records work for this, and the cases are still sealed records.

C# A generic Result type with Bind

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Bind (sometimes called then) chains steps that can each fail: if the first step failed, the error flows through unchanged and the second step never runs. The input line 9 has one word, so the list pattern in ParseTwo falls to the var parts arm. This style (sometimes called railway-oriented programming) is covered further in Exception Filters and Error Handling Patterns. Use it where failure is common and should be handled locally; keep exceptions for the unexpected.

Records with collections and the with expression

Pattern-matched state machines often update one field and leave the rest. The with expression makes that cheap to write for any record case. Remember that records are shallowly immutable: a record holding a List<T> still has a mutable list inside, so prefer ImmutableArray<T>, IReadOnlyList<T> or collections you never mutate (see immutable collections).

C# Updating states with with expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you run this you will see Approved { Title = Release notes, Signatures = System.String[] }: records print arrays by type name, not by content. That is a good reminder that the generated ToString and equality are shallow. Two records holding equal arrays are not equal, because arrays compare by reference. Use ImmutableArray<T> or write your own Equals when you need content equality of collections.

Unions in the language: a preview

The pattern above is a workaround for a missing feature. The C# language team has been designing first-class unions (declared types that hold one of several case types, with compiler-checked exhaustive switches and no need for a _ arm). At the time of writing, the feature is a proposal and available only in preview builds; the final syntax and the version number may differ, so do not build production code on it yet. The proposal's shape looks roughly like this (read-only; it does not compile on the stable compiler used here):

C#
// PROPOSED syntax, subject to change; does NOT compile with C# 14
public union Pet(Cat, Dog, Bird);

string Describe(Pet pet) => pet switch
{
    Cat c => $"cat {c.Name}",
    Dog d => $"dog {d.Name}",
    Bird b => $"bird {b.Name}",
    // no discard needed: the compiler knows these are all the cases
};

The abstract record plus sealed record approach you learned here will keep working and will be easy to migrate, because the cases are already distinct types and the switch expressions are already written in the same style.

When to use this style, and when not to

Use it when

  • data is genuinely "one of N shapes" with different fields per shape;
  • you add operations more often than cases;
  • you want invalid combinations to be impossible to construct;
  • immutability helps (state history, concurrency, testing).

Avoid it when

  • new cases appear all the time and you do not control all switches (a plugin system wants interfaces and virtual methods);
  • the behavior belongs naturally to the type and callers should not know about cases;
  • performance is critical on tiny values and allocations hurt (each case is a heap object; consider readonly record struct or a struct with a tag, at the price of clumsier code).

Nest the case records inside the abstract base (Shape.Circle) to give them a clear namespace and to let private protected seal the family. Keep one switch per operation, and give each switch a throwing default so a forgotten case fails loudly in tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a private protected constructor on the abstract base record achieve?

    private protected means accessible to derived types within the same assembly and from the containing type, so nested sealed records can derive but unrelated code cannot add new cases.
  2. 2. In the order state machine, why does the final arm return a Failed state instead of throwing?

    An illegal event is an ordinary outcome of external input. Returning a Failed state keeps the machine total and lets the caller decide what to do.
  3. 3. Which pattern in Simplify says 'adding zero on the left returns the right operand'?

    The tuple of simplified operands is matched with a positional pattern. Expr.Num(0) is a positional record pattern with a constant, var x captures the other operand.
  4. 4. Why are two records with equal arrays not equal to each other?

    Record equality is member-wise using each member's Equals. Arrays do not override it, so two distinct arrays with the same contents are different. Use ImmutableArray<T> or custom equality.
  5. 5. What is the main benefit of Result<T> over throwing exceptions for parse errors?

    A result type makes both outcomes explicit in the signature. For failures that are routine, it avoids the cost and control-flow surprises of exceptions.

Summary

  • Model "one of several shapes" with an abstract record whose constructor is private protected, and one sealed record per case, ideally nested in the base.
  • Write operations as switch expressions over the cases; positional patterns pull out the data, and a throwing _ arm catches cases you forgot until language-level unions exist.
  • State machines become a table of (state, event) patterns, with each state holding exactly the data it needs and illegal states unrepresentable.
  • Expression trees and interpreters fit naturally; nested positional patterns make rewrite rules (simplification) read like algebra.
  • A generic Result<T> with Ok and Fail cases makes expected failure part of the type.
  • Records are shallowly immutable and compare members with Equals: arrays and lists inside them are shared and compared by reference.
  • First-class union types are a proposal; this record style is the stable approach today and migrates easily.

Next: What's New in C# 8 to 14