Union types in C# | DEM304
Mads Torgersen and Dustin Campbell explore the upcoming union types feature in C#, focusing on how unions represent closed sets of possible shapes (often seen in wire protocols) and how that enables cleaner, more confident consuming code.
Overview
Union types are presented as a way to model a fixed (closed) set of alternatives in a single type, improving readability and correctness when handling multiple possible outcomes.
Key ideas
Unions as closed sets of data shapes
- Unions model a known, finite set of possible shapes.
- This is commonly useful when consuming data formats and wire protocols where a value can be one of several well-defined forms.
Cleaner consuming code
- The session emphasizes expressing intent clearly in code that consumes union values.
- A major benefit is increased confidence that all cases are handled.
Exhaustive handling with switch
- The presenters demonstrate exhaustive
switchhandling across union cases. - The examples include handling both success and error cases, highlighting how unions can make these flows more explicit.
Implementation approach (struct-based)
- The session explains an implementation approach using
structs. - Discussion includes internal design choices intended to keep unions efficient.
Performance considerations
- Performance trade-offs are discussed, including when custom/manual union implementations may be appropriate.
- The presenters cover considerations around internal struct design and how it impacts performance.
Patterns and conventions
- The session describes C# feature patterns where developers can implement conventions themselves.
- It also summarizes what manual union writing looks like today and how the language feature aims to improve that experience.
Preview and tooling
- The conclusion references a multi-year design process.
- Preview availability is mentioned for Visual Studio and VS Code.