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 astruct wiproperty. 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 amarker inteattribute 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#.
Post #2265
19.5K

Explore union types in C# 15
- ❤ 15
- 👨💻 4
- 👎 2
- 👍 1