Hasty Briefsbeta

Bilingual

dotNET (OK, C#) gets union types

a day ago
  • #Unions
  • #Programming
  • #C#
  • Unions are a new feature in C# 15 and .NET 11, allowing types to represent multiple different cases.
  • They are useful for scenarios like handling different OS record types (Windows, Linux, MacOS) without needing a common base class.
  • The union keyword creates a union type, which can be instantiated via constructors or implicit conversions.
  • Switch expressions provide a safe way to handle union types, with compiler-enforced exhaustiveness checks.
  • Union types are implemented as structs with an IUnion interface and a Value property holding the inner object.
  • Custom union implementations can avoid boxing for performance by using TryGetValue methods for each case type.
  • Features like union member providers, closed enums, and closed hierarchies are planned for future releases.