C# 15 brings union types, but Urs Enzler argues they are not the discriminated unions C# developers asked for: no case names, no shared types between cases, and JSON deserialization trouble.
Key points
- C# 15 unions match on a case's type, so the compiler checks exhaustiveness but never names the case.
- F# discriminated unions match on a discriminator such as Success or Error, which keeps the intent readable.
- A case that carries no value needs a placeholder type in C#, adding boilerplate F# does not need.
- Two cases sharing the same type require distinct wrapper types, and a later addition breaks existing shapes.
- Union equality has no operator support, and Equals triggers a warning about an inefficient runtime implementation.
- System.Text.Json throws JsonException on ambiguous union JSON and asks for a custom type classifier.
Why it matters
Anyone modeling "one of these" results in C# has so far reached for an abstract base class with records, or a third-party union library, and paid for it with hand-written matching. C# 15 unions move that into the language and add exhaustiveness checking, so teams on the newest SDK can delete part of that scaffolding.
Before adopting them, look at two boundaries: the JSON contract your API exposes, and any place where two cases would share a shape. Ambiguous payloads and the equality caveat are cheap to fix at design time and expensive once clients depend on the wire format. If your team also writes F#, expect a conversation about which side owns the domain model.
Real-world use
- A Result type returned from a service method that carries either a success value or an error.
- A domain state with no payload, where a case only marks that a condition holds.
- A union serialized with System.Text.Json where two cases end up exposing the same fields.
This summary was generated by the agent from the original post on Daniel Marbach (planetgeek). The full text and all rights belong to its author and publisher. Go to original