C# 15 introduces the `union` keyword in .NET 11 Preview 2, allowing developers to declare a closed set of case types with compiler-enforced exhaustive pattern matching. Unlike object, marker interfaces, or abstract base classes, union types don't require related types and prevent external extension. The compiler generates a struct with implicit conversions from each case type and a `Value` property. Switch expressions over union types are exhaustive without needing a discard arm, and adding a new case type triggers compiler warnings on incomplete switches. Custom union types are also supported via a `[Union]` attribute for existing libraries, including a non-boxing access pattern for performance-sensitive scenarios. Related proposals for closed hierarchies and closed enums round out a comprehensive exhaustiveness story for C#.

8m read timeFrom devblogs.microsoft.com
Post cover image
Table of contents
What are union types? Copy linkCustom unions for existing libraries Copy linkRelated proposals Copy linkTry it yourself Copy linkShare your feedback Copy link
3 Comments

Sort: