C# 15 introduces native union types in .NET 11 preview

Original: .NET (OK, C#) finally gets union types

Why This Matters

Major language enhancement brings functional programming patterns to C#

Microsoft's .NET 11 preview 4 introduces native union types to C# 15 using the new union keyword. The feature allows developers to create types that can represent multiple different data types safely, addressing a long-requested functionality from the functional programming world.

Union types, commonly used in functional languages like F#, TypeScript, and Rust, are finally coming to C# 15 in .NET 11. The feature uses a new union keyword to define types that can represent multiple different data structures. For example, developers can create 'public union SupportedOS(Windows, Linux, MacOS)' to handle operating system types safely. Previously, developers had to use workarounds like base classes, object instances, or enum tags. The union types support implicit conversion and explicit instantiation with 'new SupportedOS(new MacOS("Tahoe", 25))'. This addresses years of community requests for better type safety when dealing with data that could be one of several unrelated types.

Source

andrewlock.net — Read original →