C# 15 adds union types — a long-requested tool lands in .NET 11 Preview 2

What changed
Microsoft has introduced a native union type to C# 15, shipped in .NET 11 Preview 2. The new union keyword declares that a value is exactly one of a closed set of types, and the compiler enforces exhaustive pattern matching. Think discriminated unions from F# or sum types in other languages — but redesigned to feel like C# rather than a foreign import. Finally, you can compose unrelated types (string and Exception, say) into a single, compiler-verified contract.
How it works
A single line like union Pet(Cat, Dog, Bird) creates a Pet type that implicitly converts from each case type; assign a Dog and Pet.Value holds a Dog. The compiler will refuse assignments from types outside the declared set, and switch expressions become exhaustiveness-checked at compile time — no sneaky runtime surprises. Nullability is integrated: if any case type is nullable, switches must include a null arm; the default value of a union struct has a null Value, so pet = default; can be handled explicitly.
Why it matters
This is the kind of quality-of-life change that quietly reshapes APIs and error handling. No more brittle marker-interface patterns or object-typed grab bags. Want safer return types, cleaner ADT-style code, or fewer runtime checks? Union types give you that without forcing a paradigm shift — they slot into existing pattern matching and type systems. For developers who’ve been waiting for something like this, there’s relief here: the compiler does the heavy lifting, catching missing cases at build time, not when your users hit a bug.
Sources: devblogs.microsoft.com/dotnet, Hacker News
Comments