C# 15 introduces union types for improved code safety
C# 15, released with .NET 11, introduces a new `union` keyword that allows a type to hold exactly one value from a fixed set of options, enhancing compiler-checked exhaustive matching.
C# 15, part of the .NET 11 release on November 10, 2026, now includes a union keyword. This feature addresses a long-standing problem where developers had to use workarounds like abstract base classes to ensure all possible cases of a type were handled, often leading to runtime errors if a new case was forgotten.
A union type ensures that a value is precisely one of a predefined set of options. For instance, a TrafficLight union could only be Red, Yellow, or Green, never a combination or an unlisted color. This explicit definition allows the compiler to verify that all cases are handled during pattern matching, eliminating the need for default error branches like _ => throw new InvalidOperationException("Unsupported type").
Case types within a union can be existing types, including built-in types or types from other libraries, and they convert to the union automatically. Pattern matching directly inspects the value stored inside the union, simplifying code and improving type safety. This new feature aims to make C# code more robust and less prone to errors caused by unhandled type variations.