Sébastien Rigaux

C# 15 unions: exhaustive matching, with boxing to consider

ArticleC#.NET
View resource

andrewlock.net

C# 15 introduces the union keyword to represent a value drawn from several types without forcing them into a base class or losing their type information in object. Andrew Lock shows how switch expressions enforce handling every case, and how to declare unions such as Result<T>.

One performance detail to weigh: the generated implementation stores the value in an object, boxing value types. The article demonstrates a custom implementation using TryGetValue to avoid boxing in switch expressions.

C# code showing Windows, Linux and MacOS records, followed by a SupportedOS union containing those three types.