Hasty Briefsbeta

Bilingual

Explore union types in C# 15

12 hours ago
  • #Exhaustive Pattern Matching
  • #C# 15
  • #Union Types
  • C# 15 introduces union types with the 'union' keyword, allowing a value to be exactly one of a fixed set of types.
  • Union types provide compiler-enforced exhaustive pattern matching, ensuring switch expressions cover all case types without a default branch.
  • They solve issues from previous approaches like using 'object' or inheritance, as they compose unrelated types into a closed set.
  • Examples include simple declarations like 'Pet(Cat, Dog, Bird)' and utility unions like 'OneOrMore<T>' for single values or collections.
  • Custom union types can be created using attributes for compatibility with existing libraries, with optional non-boxing access patterns.
  • Union types are part of a broader exhaustiveness roadmap including closed hierarchies and closed enums.
  • Available in .NET 11 Preview 2, with IDE support coming soon; early preview requires declaring polyfill types manually.
  • Feedback is encouraged to shape the final design, and features like the 'is' operator and null handling are supported.