.NET 11 Preview Introduces Union Types in C# 15
Microsoft has released .NET 11 Preview with one of the most requested C# language features: native union types. Available via the new 'union' keyword in C# 15, the feature allows developers to define types that can represent multiple different types without inheritance hierarchies or boxing to object. The syntax is straightforward: 'public union SupportedOS(Windows, Linux, MacOS);' creates a type that can hold any of the three record types. The compiler enforces exhaustive pattern matching in switch expressions, eliminating a common source of runtime errors. Union types support implicit conversion from their case types and implement an IUnion interface. The feature is implemented as a compiler enhancement, meaning it can even target earlier .NET runtime versions, though full runtime support requires .NET 11 Preview 4+. Developers need to enable the preview language version in their .csproj files to use unions. The addition brings C# closer to languages like TypeScript, Rust, and F# which have had union types for years, and is particularly useful for modeling domain concepts, result types, and optional values.
Union types eliminate a long-standing pain point in C# and will simplify codebases that previously relied on awkward workarounds like base classes, object boxing, or tagged unions. This is a signal that Microsoft is serious about bringing functional programming patterns to the mainstream .NET ecosystem.
Do I need .NET 11 runtime to use union types?
No, the union type feature is a compiler enhancement. You need the .NET 11 SDK with preview language version enabled, but you can target earlier runtime versions like .NET 8. For runtimes before .NET 11 Preview 4, you'll need to add helper types manually.