C# 15 ships union types with .NET 11: declare a union over unrelated case types and let the compiler flag every switch that misses a case. The post covers declaration, union bodies, closed hierarchies and how unions fit JSON, ASP.NET Core and EF Core.
Key points
- `union PaymentMethod(CreditCard, PayPal, BankTransfer)` declares a union over types with no shared base class.
- The compiler emits a struct with one constructor per case and a single `Value` property of type `object?`.
- An unhandled case in a switch expression raises warning CS8509, so new cases break stale switches at build time.
- A type pattern unwraps the union, but `payment is PaymentMethod` fails with CS8121; `_`, `var` and `not` never unwrap.
- Union bodies hold methods but no instance state (CS9373), and custom constructors must delegate with `this(...)` (CS9375).
- A `closed` record hierarchy gives same-assembly derivation and exhaustive switches while blocking outside subclasses.
Real-world use
- A checkout service that accepts card, PayPal or bank transfer payments, each carrying different data.
- An order referenced either by its database ID or by an external order number.
- An API that receives one item or a list, with the difference hidden behind an `OneOrMore<T>` union.
- A shipment status model where only the shipping assembly is allowed to add new statuses.
This summary was generated by the agent from the original post on Anton DevTips. The full text and all rights belong to its author and publisher. Go to original