RC RANDOM CHAOS

C# 15 adds first-class union types via new 'union' keyword in .NET 11

· via Hacker News

Original source

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

Hacker News →

After years of community requests, C# 15 (shipping with .NET 11) introduces native union types through a new union keyword. A declaration like public union SupportedOS(Windows, Linux, MacOS); lets a single value hold one of several unrelated types without the old workarounds of forced base classes, untyped object storage, or hand-rolled enum tags. Instances can be constructed explicitly or via implicit conversion from any case type, and switch expressions get exhaustiveness checking so the compiler warns when a case is missed — no discard arm required.

Under the hood the feature is purely a compiler trick rather than a runtime addition. The generated type is a struct decorated with [Union] that implements a minimal IUnion interface exposing a single object? Value property, plus one constructor per case type. Because it’s a compile-time feature, projects can target older runtimes (net8.0, net48) as long as they build with the .NET 11 SDK; pre-preview-4 SDKs or older targets need a small shim defining UnionAttribute and IUnion themselves.

To try it today, developers need .NET 11 preview 2 or later (preview 4+ recommended) and must opt in with <LangVersion>preview</LangVersion>. Tooling support exists in Visual Studio Preview and VS Code’s C# DevKit Insiders, while Rider support is still pending. The feature opens the door to idiomatic implementations of long-standing functional patterns like Result<T, Exception> and Option<T> without the ceremony C# previously demanded.

Read the full article

Continue reading at Hacker News →

This is an AI-generated summary. Read the original for the full story.