Other

What's New in C# 15: Union Types, Closed Hierarchies and Practical Examples

Ottorino Bruni Ottorino Bruni
Other

C# 15 finally answers the long-standing call for discriminated unions with a `union` keyword, and adds `closed` hierarchies so the compiler can enforce exhaustive pattern matching. A practical walkthrough for .NET developers who want domain models like payment results and payment events that make invalid states unrepresentable.

Key points

  • `union PaymentResult(Paid, Declined, Pending)` declares a fixed set of cases in one type.
  • The compiler emits implicit conversions from each case type, and unrelated or generic types can be combined.
  • Switch expressions drop the `default` arm; a missing case raises warning CS8509, which can be promoted to an error.
  • The generated union is a struct with an `object?` `Value` property, so value-type cases get boxed.
  • A `default` union holds a null `Value`, meaning an empty state exists even with non-nullable cases.
  • A `closed record class` allows derivation only inside its own assembly, and that restriction is not transitive.

Why it matters

The developers most affected are those who model business rules as a fixed set of independent outcomes — payment approved, declined, sent for manual review — where `object` returns or nullable-field records currently stand in for a checked type. Day to day, switch expressions lose their `default` arm, and adding a case surfaces warning CS8509 everywhere it matters, which is exactly the kind of silent gap large codebases tend to hide.

Two limits are worth knowing before adopting it. The generated union is a struct, so value-type cases are boxed and allocate on hot paths, and a `default` union can still carry a null `Value`, so the "no case at all" state survives. Retrofitting existing inheritance hierarchies with `closed` is also not free: because the restriction is not transitive, intermediate classes must be marked too and leaves kept sealed.

Real-world use

  • An e-commerce payment service returning independent outcomes such as Paid, Declined and Pending from one method.
  • A payment workflow modelling PaymentInitiated, PaymentAuthorized and PaymentFailed events that share a PaymentId base.
  • A reusable generic union such as `OneOrMore<T>` that accepts either a single item or a collection.

This summary was generated by the agent from the original post on Ottorino Bruni. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message