Skip to content

Unions and Closed Hierarchies ​

TypeScript union types (Car | Scooter | Train) are one of the best parts of the language. They are also gone at runtime, so you end up with a hand-rolled kind field, a switch, and (at the API boundary) a Zod schema to check that the incoming JSON really is one of the shapes you claimed.

C# 15 (shipped with .NET 11) finally closes this gap with two features: unions (union) and closed hierarchies (closed). Both keep their type information at runtime and both give you compiler-checked exhaustive switch expressions. Check out what's new in C# 15 for the full release notes.

Short on time?

Unrelated types you want to treat as "one of these": use a union. Variants that share fields and behavior: use a closed hierarchy. There's a comparison table at the bottom.

The TypeScript Starting Point ​

Here's the tagged (discriminated) union pattern that most TypeScript backends settle on:

ts
type Scooter = { kind: "scooter"; electric: boolean };
type Car = { kind: "car"; seats: number };
type Train = { kind: "train"; type: "bullet" | "normal" };

type TransitOption = Scooter | Car | Train;

function describe(transit: TransitOption): string {
  switch (transit.kind) {
    case "scooter": return `Scooter (electric: ${transit.electric})`;
    case "car": return `Car with ${transit.seats} seats`;
    case "train": return `${transit.type} train`;
    default: {
      // 👇 Compile-time exhaustiveness trick
      const unreachable: never = transit;
      return unreachable;
    }
  }
}

It works, but notice the ceremony: the kind tag you maintain by hand and the never trick for exhaustiveness. At runtime, describe({ kind: "plane" } as any) sails right through the default branch. Read more about discriminated unions in the TypeScript handbook.

Type Unions (union) ​

A C# union declares a type that holds exactly one of a fixed list of case types. The case types can be completely unrelated: no shared base class, no shared interface.

ts
type Scooter = {
  kind: "scooter";
  electric: boolean;
};
type Car = { kind: "car"; seats: number };
type Train = { kind: "train"; type: string };

type TransitOption = Scooter | Car | Train;

function chooseTransit(
  numPeople: number
): TransitOption {
  if (numPeople === 1)
    return { kind: "scooter", electric: true };
  if (numPeople < 5)
    return { kind: "car", seats: 5 };
  if (numPeople < 7)
    return { kind: "car", seats: 8 };
  return { kind: "train", type: "bullet" };
}
csharp
record Scooter(bool Electric);
record Car(int Seats);
record Train(TrainType Type);

// 👇 One line; no `kind` tags
public union TransitOption(
  Scooter, Car, Train
);

TransitOption ChooseTransit(int numPeople) =>
  numPeople switch {
    1 => new Scooter(true),
    < 5 => new Car(5),
    < 7 => new Car(8),
    _ => new Train(TrainType.Bullet)
  };

Every arm above hands back a plain case type and C# converts it to TransitOption implicitly. The records carry their real type at runtime, so there's no kind field to forget or mistype.

Checking and Switching ​

Pattern matching looks through the union to the case inside:

ts
const transit = chooseTransit(6);

console.log(
  transit.kind === "car" && transit.seats === 8
); // true
csharp
var transit = ChooseTransit(6);

Console.WriteLine(
  transit is Car { Seats: 8 }
); // True
Console.WriteLine(
  transit is Scooter
); // False

The switch expression is where this pays off. No tag to read and no never trick; the compiler already knows the full list of cases:

csharp
string Describe(TransitOption transit) => transit switch {
  Scooter s => $"Scooter (electric: {s.Electric})",
  Car c => $"Car with {c.Seats} seats",
  Train t => $"{t.Type} train"
};

Console.WriteLine(Describe(ChooseTransit(7))); // "Bullet train"

Leave out the Train arm and you get warning CS8509 (the switch expression does not handle all possible values). Add a fourth case to the union later and every switch that forgot it lights up. No dummy _ => fallback needed.

Resist the urge to add _ =>

A discard arm makes the warning go away, and it also swallows the next case you add to the union. I leave it out on purpose so the compiler keeps tapping me on the shoulder.

default and null ​

A union is a struct, which means default(TransitOption) is a legal value that holds no case at all. If it reaches a switch with no null arm, you get a SwitchExpressionException at runtime.

I add an explicit null arm:

csharp
string Describe(TransitOption transit) => transit switch {
  Scooter s => $"Scooter (electric: {s.Electric})",
  Car c => $"Car with {c.Seats} seats",
  Train t => $"{t.Type} train",
  null => "Nothing selected" // 👈 Handles `default` and keeps exhaustiveness checks alive
};

Console.WriteLine(Describe(default)); // "Nothing selected"

The compiler won't force this on you when all the cases are non-nullable (it compiles fine without it, as it did for me), but if one of the cases is nullable, leaving out null raises CS8655. Either way, it's the cheaper fix compared to a _ => arm. More on null handling in Nulls.

Generic Unions ​

Unions can be generic, so the "maybe a value" shape is a one-liner:

ts
type None = { kind: "none" };
type Some<T> = { kind: "some"; value: T };
type Option<T> = None | Some<T>;

function findContact(
  firstName: string
): Option<Contact> {
  if (firstName === "Ada") {
    return {
      kind: "some",
      value: {
        firstName: "Ada",
        lastName: "Lovelace"
      }
    };
  }
  return { kind: "none" };
}
csharp
record Contact(
  string FirstName,
  string LastName
);

record None;
record Some<T>(T Value);

public union Option<T>(None, Some<T>);

Option<Contact> FindContact(
  string firstName
) => firstName == "Ada"
  ? new Some<Contact>(
      new Contact("Ada", "Lovelace")
    )
  : new None();

And it switches the same way:

csharp
var message = FindContact("Ada") switch {
  Some<Contact> found => $"Hello, {found.Value.FirstName}",
  None => "Who?",
  null => "Who?"
};

This is the closest C# gets to the Option or Result types that folks reach for in Rust or fp-ts. Read more about type parameters in Generics.

Under the Hood ​

Two details worth knowing before you put unions on a hot path:

  • The compiler turns public union TransitOption(...) into a struct marked with [Union] that implements System.Runtime.CompilerServices.IUnion. It stores the active case in a single object? Value, which means value-type cases get boxed.
  • If boxing shows up in a profile, you can write your own [Union] struct that exposes single-argument case constructors plus Value, HasValue, and typed TryGetValue members. The compiler treats it like any other union.

Most of the time the generated version is fine. I'd only hand-roll one after measuring.

JSON round-tripping

System.Text.Json in .NET 11 understands unions and writes the active case directly. We'll look at that in JSON Serialization.

Closed Hierarchies (closed) ​

Sometimes the variants aren't unrelated at all. A CardPayment and a BankTransfer both have an amount, and you'd like to write that field once. That's an inheritance hierarchy, and what C# was missing is a way to say "these are all the subclasses, and nobody else gets to add more."

That's closed:

ts
// No way to close a class hierarchy in TS,
// so we fall back to a tagged union again
type CardPayment = {
  kind: "card";
  amount: number;
  last4: string;
};

type BankTransfer = {
  kind: "bank";
  amount: number;
  iban: string;
};

type Payment = CardPayment | BankTransfer;

function fee(payment: Payment): number {
  switch (payment.kind) {
    case "card": return payment.amount * 0.029;
    case "bank": return 0.5;
  }
}
csharp
// 👇 `closed` base: implicitly abstract
public closed record Payment(decimal Amount);

public sealed record CardPayment(
  decimal Amount,
  string Last4
) : Payment(Amount);

public sealed record BankTransfer(
  decimal Amount,
  string Iban
) : Payment(Amount);

decimal Fee(Payment payment) => payment switch {
  CardPayment card => card.Amount * 0.029m,
  BankTransfer => 0.50m
  // 👆 No `_` arm needed
};

Same exhaustive switch, but now Amount is declared once on the base type and every case gets it. Add a Wallet payment type later and Fee produces a CS8509 warning until you handle it.

The same works with plain classes and shared behavior:

csharp
public closed class Vehicle(int seats) {
  public int Seats { get; } = seats;

  public string Describe() => $"{GetType().Name} with {Seats} seats";
}

public sealed class Car(int seats) : Vehicle(seats);
public sealed class Suv(int seats) : Vehicle(seats);
public sealed class Minivan(int seats) : Vehicle(seats);

var vehicle = new Suv(7);
Console.WriteLine(vehicle.Describe()); // "Suv with 7 seats"

new Vehicle(5); // ❌ CS0144: cannot create an instance of the abstract type 'Vehicle'

The rules I keep in my head:

  • A closed base is implicitly abstract; you can't new it.
  • Direct subclasses must live in the same assembly (project) as the base. Code in other projects can use the hierarchy but can't add to it.
  • It works for classes and records only. closed interface is not allowed.
  • Mark the leaf classes sealed. An open leaf can still be subclassed from another assembly, and that quietly reopens the hierarchy you just closed.

A word on TypeScript

TypeScript has no sealed or closed for classes, which is why the left side falls back to a tagged union. If your TypeScript variants share a lot of behavior, you're probably also writing a base class and a pile of instanceof checks. This is the case where C# is a clear step up.

Union or Closed? ​

Questionunionclosed hierarchy
Do the cases share a base type?No need; cases can be unrelated (even string and int)Yes; one base class or record
Shared fields and behavior?Not really; each case stands aloneYes; declare once on the base
Who can add a case?Only the person editing the union declarationOnly code in the declaring assembly
Exhaustive switch?Yes (CS8509)Yes (CS8509)
Can be default/null?Yes (struct); add a null armNormal reference rules (it's a class)
AllocationBoxes value-type cases unless you write a custom [Union]Normal class allocation
TypeScript analogA | B | CTagged union plus a shared base type

Rough rule: if you find yourself wanting a base class just so the types can go in the same variable, use a union. If the base class already exists because the variants share real state, use closed.

Pre-C# 15 targets

If you're stuck on .NET 10 or earlier, OneOf and dunet get you most of the way there for unions. For hierarchies, the usual workaround is a private constructor on the base type with the subclasses nested inside it.

Run the Examples ​

Each snippet on this page has a runnable file-based app in the repo (you need the .NET 11 SDK, see Getting Started):

FileWhat it shows
transit-union.csTransitOption union, is patterns, exhaustive switch, null arm
generic-option-union.csGeneric Option<T> union
closed-payment-hierarchy.csclosed record hierarchy with a shared Amount
closed-vehicle-hierarchy.csclosed class hierarchy with shared behavior
shell
dotnet run src/csharp/fileapps/basics/unions-and-closed-hierarchies/transit-union.cs

Official docs: union, closed, and what's new in C# 15.