Mit .NET 11 kommen union types und closed hierarchies nach C# - aber wie benutzt du bzw. dein Agent sie richtig?
Die gerade veröffentliche neue Version von .NET und C# bringt spannende Features mit sich. Die werden allerdings in bestehenden Codebasen noch nicht genutzt, und die LLMs sind nicht auf ihre Verwendung trainiert. Wie können wir also das meiste aus der neuen Version rausholen?

Dieser Frage sind wir nachgegangen, und haben eine Entscheidungshilfe formuliert, die Mensch und Maschine zugleich darin anleitet, in welcher Situation welches Konstrukt das passende ist. Wird Code neue geschrieben oder geändert, kann er dabei gegen die Guidelines geprüft und angepasst werden. Diese Guidelines gehen davon aus, dass der Code bereits nach Konzepten der funktionalen Programmierung geschrieben ist. Sie lassen sich aber auch für andere Codebasen verwenden bzw. dafür anpassen. Die Entscheidungshilfe für die Auswahl des passenden Konzepts (union, closed oder offene Vererbung) bleibt allgemeingültig.
Wer die Vorteile von Union Types auch in älteren Projekten verwenden möchte, darf gerne auf unser Paket https://www.github.com/bluehands/Funicular-Switch zurückgreifen, das in den Guidelines für genau diesen Fall bereits erwähnt wird.
Hier also die Guidelines für union types und closed hierarchies in C# 15 / .NET 11:
Union types (sum types)
Use sum types to make illegal states unrepresentable. If a value is "either A or B", do not model it as a product (tuple,`bool` + `out`, enum + nullable fields).
Check `LangVersion` and `TargetFramework` first: `union` and `closed` need C# 15 / .NET 11. Otherwise follow "Older C# / .NET" below.
When to use what
First matching row wins.
| Situation | Use |
|---|---|
| Others (other assemblies, plugins) must be able to add cases | open inheritance / interface |
| Boxing is a measured bottleneck on a hot path | hand-written `[Union]` struct implementing `IUnion` with `HasValue` / `TryGetValue` |
| Union needs fields of its own | hand-written `[Union]` type (native `union` bodies allow no instance fields) |
| Operation can fail as part of normal flow | `Result` from FunicularSwitch, not a home-grown one |
| Value may simply be missing | `Option` from FunicularSwitch instead of `null` / `bool TryX(out ...)` |
| Cases are types you do not own, primitives or other value types, or a case appears in several sum types | `union X(A, B)` |
| Any other fixed set of cases you define for this one type, including absence with domain meaning (`NotFound`, `Expired`) | `closed` hierarchy (`closed record Base; sealed record A : Base;`) |
Prefer `closed` when you define the cases yourself: cases keep their own `ToString()`, base members are available without unwrapping, there is no `default` value without content, and JSON can get a `$type` discriminator with `[JsonPolymorphic(InferClosedTypePolymorphism = true)]` on the base (without it, the base serializes as `{}`). Use `union` when the cases cannot or should not derive from a common base.
FunicularSwitch `[UnionType]` on a `partial closed` base still adds generated static factories and `Match`/`Switch` with async overloads. Use it where the project benefits from these. The generator package (`FunicularSwitch.Generators`) adds no runtime dependency.
With `union` or `closed`, new functions are cheap and new cases touch every consumer. With open inheritance it is the other way round.
Rules
- Each case carries exactly the data it needs. No nullable fields that are only valid "for some kinds".
- Define cases as `record`s. Use `readonly record struct` only for cases without reference fields, since `default` of a struct case is always possible. Native `union` boxes value types anyway, so do not pick structs to save allocations.
- Consume unions with `switch` expressions and type patterns. Do not use `switch` statements: the compiler checks exhaustiveness only for expressions. If you only need side effects, still use an expression and return a value from each arm.
- Do not use `_` as a catch-all: it hides new cases from the exhaustiveness warning.
- For native `union` types handle `null` explicitly: a `default` union has `Value == null`.
- Type patterns (`Dog d`) test the content; property patterns without a type (`{ Name: ... }`) test the union itself.
- A native union's `ToString()` returns the union's type name, not the stored value. Use `.Value` for logging and string interpolation, or override `ToString()` in the union body.
- `closed` implies `abstract`. `union` bodies may have members but no instance fields.
- Do not use exceptions for expected failures; return a `Result` and chain with `Map` / `Bind`.
Older C# / .NET
Without `union` and `closed` the rules above still apply:
- Model the union as an `abstract` base record/class with an internal constructor and `sealed` cases in the same assembly, so outsiders cannot add cases.
- Get exhaustiveness from FunicularSwitch `[UnionType]` (generated `Match`/`Switch`, a new case breaks every call). Declare the base type `partial`, the generator adds code to it. A plain `switch` over an abstract base needs a `default` arm and gives no warning for new cases.
- Use `Result` / `Option` from FunicularSwitch, not a home-grown one.
- When the project moves to C# 15 / .NET 11, replace `abstract` with `closed` instead of rewriting to `union`.



