.NET 11 Preview 4 brings native union types to C# 15
The upcoming release introduces compiler-generated structs for handling multiple distinct types, though standard implementations currently incur heap allocation costs for value types.
Microsoft has introduced native support for union types in C# 15, a feature available in the .NET 11 Preview 4 build. This development addresses a long-standing request from developers, bringing functionality previously restricted to functional programming languages such as F#, TypeScript, and Rust. The update allows variables to represent one of several distinct types, facilitating common patterns like Result or Option types that require explicit handling of multiple potential states.
The implementation relies on a compiler-generated struct that implements the IUnion interface and is marked with a [Union] attribute. Developers can utilise switch expressions to handle the different cases, with the compiler enforcing exhaustiveness checks to ensure all allowed values are addressed. If a case is omitted, the compiler issues a warning, although nullable types require explicit handling within the switch logic.
While the standard generated union type is a struct with a single object field, this approach causes value types to be boxed onto the heap. This allocation can be undesirable in performance-critical paths where transparency and efficiency are paramount. To mitigate this, the feature supports custom non-boxing implementations using a TryGetValue pattern, allowing developers to optimise memory usage for specific use cases.
IDE support is currently available in Visual Studio Preview and VS Code's C# DevKit Insiders, while support for JetBrains Rider remains pending. The union support is implemented as a compiler feature, meaning it is available on earlier runtimes if the .NET 11 SDK is used, though helper types are required for runtimes prior to .NET 11 Preview 4.
The feature is currently in preview, and details may change before the final release. Future roadmap items include potential improvements to exhaustiveness checks, though these are not guaranteed for .NET 11. Developers can currently implement custom union types by implementing the IUnion interface and adding the [Union] attribute, facilitating migration from existing libraries.


