Introducing Union Types in C# 15
By Bill Wagner

AI Summary
Union types have been a highly anticipated feature in C#, and with C# 15, they're finally here. These types allow a value to be exactly one of a fixed set of types, with the compiler ensuring exhaustive pattern matching. This feature is familiar to those who have used discriminated unions in F# or similar languages, but C# unions are tailored for a native experience, integrating seamlessly with existing pattern matching and language features.
Before union types, methods returning multiple possible types had to rely on less-than-ideal solutions like using the object type or marker interfaces, which lacked exhaustiveness and required a common ancestor. Union types solve these issues by declaring a closed set of case types, ensuring that switch expressions cover all possibilities without needing default branches.
For example, declaring a union type Pet with case types Cat, Dog, and Bird allows variables to hold any of these types, with the compiler providing implicit conversions. This ensures that switch expressions are exhaustive, catching missing cases at build time. The union type's Value property is automatically checked, simplifying the syntax.
Union types are not only syntactic sugar but also enable new design patterns. For instance, the OneOrMore<T> union type can represent either a single value or a collection, with methods like AsEnumerable() to normalize input. This flexibility is crucial for APIs that handle both single items and collections.
Existing libraries with union-like types can also benefit from this feature without changing their implementation. By using the UnionAttribute, these libraries can integrate with C# 15's union syntax, enhancing performance by avoiding boxing for value types.
Union types are part of a broader vision for C# that includes closed hierarchies and enums, all contributing to a comprehensive exhaustiveness story. While union types are available in .NET 11 Preview 2, the community's feedback is essential to refine and finalize their design. Developers are encouraged to experiment with union types and provide feedback to shape their future.
Key Concepts
Union types allow a variable to hold a value that is exactly one of a fixed set of types, with the compiler ensuring exhaustive pattern matching.
Pattern matching is a feature that allows checking a value against a pattern and, if it matches, extracting data from it.
Category
ProgrammingOriginal source
https://devblogs.microsoft.com/dotnet/csharp-15-union-types/More on Discover
Summarized by Mente
Save any article, video, or tweet. AI summarizes it, finds connections, and creates your to-do list.
Start free, no credit card