C# 15 adds union types with compiler-checked exhaustive switches
C# 15, shipping with .NET 11 RC1, introduces union types that define a closed set of case types and let the compiler verify exhaustive pattern matching, emitting warning CS8509 when a new case is added. Unions compile to a struct holding an object?, so value-type cases are boxed and default yields an empty value.
- A union names a closed set of types: union LookupResult(Found, NotFound, Invalid)
- The compiler flags unhandled cases with warning CS8509
- A union is a struct with a single object? field, 8 bytes in size
- Value-type cases are boxed: 1000 ints in a union allocated 24,000 bytes
Read next
Software