Microsoft Adds Union Types to C# 15 via Struct-Backed Runtime Model
Microsoft Developer
Microsoft rejected TypeScript-style structural unions in favor of nominal, struct-lowered types because the .NET runtime requires reified type information at runtime.
C# 15 introduces first-class union types to model closed, heterogeneous sets of data shapes, addressing long-standing type-safety limitations when aggregating unrelated types without a common hierarchy. (0:00)
By default, the Roslyn compiler lowers syntactic unions into a value-type struct containing a single reference-type object field, trading zero struct-size overhead for heap boxing allocations when wrapping value types. (13:24)
Developers can override default boxing behavior by manually authoring custom non-allocating structs or retrofitting legacy types using the [Union] attribute introduced in .NET 11 Preview 4. (17:33)
Because .NET requires runtime type reification, C# rejected TypeScript's erased ad-hoc structural unions (e.g., A | B) in favor of declared, nominal union types. (21:02)
Detailed notes
## Background
Published by Microsoft Developer on YouTube on June 3, 2026, this Microsoft Build session (DEM304) features C# team members Mads Torgersen and Dustin Campbell introducing union types in C#. According to the video description, the session explores how unions model closed sets of data shapes—commonly found in wire protocols—and examines the confidence, elegance, and clean expression of intent they bring to consuming code.
## TL;DR
Mads Torgersen and Dustin Campbell unveil C#'s new union types slated for C# 15, demonstrating how they provide a pragmatic, type-safe alternative to weakly typed collections of System.Object. The speakers show how declared unions enforce compile-time exhaustiveness in switch expressions, facilitate pattern deconstruction when paired with records, and support functional members while barring extra instance state. They also explain how unions lower to an internal struct wrapping an object field, detailing how developers can write custom, non-allocating union patterns or retrofit legacy types using the [Union] attribute. Finally, they contrast C#'s nominal, runtime-reified approach with TypeScript's erased structural unions, reflecting on the five-year design journey to bring preview support to Visual Studio and VS Code.
## Atmosphere & style
The presentation carries a lighthearted, collaborative, and conversational tone, propelled by the effortless camaraderie between lead designer Mads Torgersen and engineer Dustin Campbell. Watching them bounce code and commentary back and forth feels like sitting in on a live, candid engineering whiteboard session punctuated with dry humor about San Francisco shark pets and developers who love being handed compiler errors. Beneath the casual banter lies deep technical reverence for language craft, culminating in genuine enthusiasm as they peel back the syntax to reveal the underlying struct plumbing and runtime trade-offs.
## Bulletin
- [00:00](https://www.youtube.com/watch?v=7qW92AwlrjM&t=0s) C# 15 introduces first-class union types to model closed, heterogeneous sets of data shapes, addressing long-standing type-safety limitations when aggregating unrelated types without a common hierarchy.
- [13:24](https://www.youtube.com/watch?v=7qW92AwlrjM&t=804s) By default, the Roslyn compiler lowers syntactic unions into a value-type struct containing a single reference-type object field, trading zero struct-size overhead for heap boxing allocations when wrapping value types.
- [17:33](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1053s) Developers can override default boxing behavior by manually authoring custom non-allocating structs or retrofitting legacy types using the [Union] attribute introduced in .NET 11 Preview 4.
- [21:02](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1262s) Because .NET requires runtime type reification, C# rejected TypeScript's erased ad-hoc structural unions (e.g., A | B) in favor of declared, nominal union types.
## Key takeaways
- [00:00](https://www.youtube.com/watch?v=7qW92AwlrjM&t=0s) Union types are slated for official release in C# 15 in November, with preview bits accessible in Visual Studio and VS Code.
- [00:00](https://www.youtube.com/watch?v=7qW92AwlrjM&t=0s) C#'s design represents a tailored 'Goldilocks' compromise distinct from TypeScript's structural unions and traditional functional discriminated unions.
- [01:16](https://www.youtube.com/watch?v=7qW92AwlrjM&t=76s) Historically, aggregating disparate types required falling back to System.Object, which bypassed compiler type checking and generated non-exhaustive pattern matching warnings.
- [03:28](https://www.youtube.com/watch?v=7qW92AwlrjM&t=208s) Declaring a union type introduces implicit conversions from valid case types while barring unauthorized types at compile time.
- [03:28](https://www.youtube.com/watch?v=7qW92AwlrjM&t=208s) Pattern matching against union types provides compiler-enforced exhaustiveness checks, immediately warning developers if any variant or nullability state is unhandled.
- [06:28](https://www.youtube.com/watch?v=7qW92AwlrjM&t=388s) Union bodies permit functional abstractions such as computed properties and methods, but strictly prohibit additional instance state.
- [08:14](https://www.youtube.com/watch?v=7qW92AwlrjM&t=494s) A primary practical use case for unions is modeling wire protocols and API results by binding disparate outcome records (such as Success and Error) into a unified contract.
- [09:42](https://www.youtube.com/watch?v=7qW92AwlrjM&t=582s) Union types fully support generics, record case deconstruction, interfaces, type parameters, and overlapping case types.
- [13:24](https://www.youtube.com/watch?v=7qW92AwlrjM&t=804s) The language syntax lowers by default into an internal struct implementing the IUnion interface with a public object Value property.
- [17:33](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1053s) The pattern-based [Union] attribute allows developers to author custom non-allocating structs with dedicated fields and discriminator tags for high-throughput scenarios.
- [19:13](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1153s) Decorating existing codebase models with [Union] lets teams modernize legacy domain types without breaking binary or API compatibility.
- [21:02](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1262s) Unlike TypeScript where union types are fully erased at compile time, C# requires unions to exist as reified nominal types inspectable by the .NET runtime.
- [24:24](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1464s) The final union syntax represents approximately five years of language design iteration across the Roslyn and .NET runtime teams.
## Detailed walkthrough
### [00:00](https://www.youtube.com/watch?v=7qW92AwlrjM&t=0s) Introduction to Union Types in C# 15
Mads Torgersen, lead designer of C#, and Dustin Campbell, an engineer on the C# team, open the session against a running conference timer to unveil a long-awaited language capability: union types. Mads notes that the feature is slated for C# 15 in November, with preview bits already available for developers to test out.
```mermaid
flowchart TD
accTitle: Union Types in Language Design
accDescr: Comparison showing how C# 15 unions fit alongside TypeScript and functional programming languages.
subgraph OtherLangs["Existing Approaches"]
TS["TypeScript Unions"]
FP["Functional Discriminated Unions"]
end
subgraph CSharpApproach["C# 15 Strategy"]
CS["C# Union Types<br/>'Goldilocks / Compromise'"]
end
TS -.->|"Different paradigms"| CS
FP -.->|"Different paradigms"| CS
```
Unions exist in many environments—TypeScript has structural union types, and functional programming languages implement variations of discriminated unions—but each language treats them differently. Mads explains that C#'s design represents a deliberate, pragmatic choice tailored to the ecosystem: “They're our own little we call it Goldilocks, but you can also call it compromise version of it.” The speakers encourage attendees to set aside preconceived notions from other languages, as this demo focuses on how unions naturally fit the C# object and pattern-matching model.
- Lead designer Mads Torgersen and engineer Dustin Campbell introduce C# 15's union types at Build.
- Feature release target: November (C# 15), with active preview bits.
- C# implements a tailored design ("Goldilocks version") distinct from TypeScript or traditional functional languages.
---
[01:16](https://www.youtube.com/watch?v=7qW92AwlrjM&t=76s) The Limitations of Modeling Heterogeneous Sets with `object`
Transitioning directly into code using top-level statements, Dustin sets up an all-too-familiar scenario: working with several pre-existing types representing animals (such as dogs and cats) that were authored independently across different libraries without a shared domain model. Because these disparate types lack a common interface or base class, developers traditionally have only one recourse when aggregating them: treating every item as the universal root type, `System.Object`.
```mermaid
flowchart LR
accTitle: Legacy Fallback to Object
accDescr: Independent animal libraries falling back to a weakly typed list of object.
subgraph Libs["Disparate Libraries"]
Dog["Dog"]
Cat["Cat"]
Bird["Bird"]
Shark["Shark (Invalid)"]
end
Libs -->|"No shared hierarchy"| Obj["List<object>"]
Obj -->|"Switch without type safety"| Match["Switch Expression<br/>(Compiler Warning: Non-Exhaustive)"]
```
Dustin demonstrates iterating over a `List<object>` of pets and deconstructing each entry with a pattern-matching `switch` expression to produce a formatted string description. However, this approach completely lacks type safety. Because any reference type can satisfy `object`, accidental additions slip right past the compiler—illustrated by the presence of a `Shark` in the pet list. Mads jokes about San Francisco tastes, but notes that a shark is hardly an appropriate pet “with that many teeth.”
Beyond failing to reject unauthorized types at the collection boundary, the switch expression itself receives a compiler warning squiggle because the pattern cannot be proven exhaustive against every arbitrary object that could exist in the runtime (such as crocodiles or snails). As Mads remarks: “So this is not great, but this is sort of the best we can do in C# up until now.”
---
[03:28](https://www.youtube.com/watch?v=7qW92AwlrjM&t=208s) Declaring Union Types, Implicit Conversions, and Exhaustiveness
To solve the pet problem without altering the original animal classes, Dustin introduces the new `union` syntax:
```csharp
union Pet(Dog, Cat, Bird);
```
By defining `Pet` as a union of specific types, the collection can be strongly typed as a `List<Pet>`. Instantly, the compiler validates the collection elements. When the `Shark` entry is evaluated, compilation fails with an error: *cannot implicitly convert type Shark to Pet*. Mads highlights the dual meaning of that diagnostic: while `Shark` is barred, valid case types (`Dog`, `Cat`, `Bird`) convert implicitly to the union wrapper `Pet`.
```mermaid
flowchart TD
accTitle: Union Type Safety and Exhaustiveness
accDescr: How union types enforce implicit conversions and compiler-checked exhaustiveness.
subgraph Def["Union Definition"]
PetUnion["union Pet(Dog, Cat, Bird)"]
end
subgraph Conversions["Implicit Conversions"]
PetUnion -->|"Valid"| D["Dog / Cat / Bird -> Pet"]
PetUnion -.->|"Compile Error"| S["Shark -/-> Pet"]
end
subgraph Matching["Pattern Matching"]
D --> Switch["switch (pet)"]
Switch -->|"Covered"| Exh["Exhaustive Pattern: No Warning"]
Switch -.->|"Omit Bird or Add Nullable"| Warn["Warning: Non-Exhaustive"]
end
```
The switch expression gains immediate compiler support once the rogue `Shark` pattern arm is removed:
- **Exhaustive pattern matching:** The non-exhaustive warning completely disappears because the compiler proves that every declared variant of `Pet` is explicitly handled.
- **Missing case detection:** Commenting out a single branch (e.g., `Bird`) immediately resurrects the compiler warning, identifying exactly which variant remains unhandled.
- **Null awareness:** Changing the union signature to allow a nullable variant (such as `Bird?`) forces the switch to account for `null`, proving how tightly integrated the feature is with C#'s existing nullable reference types and exhaustiveness checking.
---
[06:28](https://www.youtube.com/watch?v=7qW92AwlrjM&t=388s) Adding Function Members and Restricting Extra State
Dustin and Mads address how developers enrich union declarations. While single-line declarations define the closed set of types, union declarations can also contain bodies enclosed in braces to declare members, just like classes or structs:
```csharp
union Pet(Dog, Cat, Bird)
{
public string Description => this switch
{
Dog d =>...,
Cat c =>...,
Bird b =>...
};
}
```
By embedding the description computation inside `Pet`, consuming code simply accesses `pet.Description`.
Mads explains the explicit architectural boundary enforced by the C# language team regarding union bodies: developers may implement functional abstractions—such as computed properties, methods, and static members—but cannot declare additional instance state. As Mads specifies: “We do draw a line at things that introduce more state because we think you should think of it as the state of this thing is just the actual dog or cat or bird that's inside it shouldn't have additional state, right that.” This guarantee preserves unions as pure wrappers over their underlying variant values.
---
[08:14](https://www.youtube.com/watch?v=7qW92AwlrjM&t=494s) Applying Unions to Real-World Wire Protocols and Results
Acknowledging audience feedback that language demos often rely on simplistic domain models like animals or students, Dustin and Mads pivot to the primary real-world use case that inspired community demand: wire protocols, API boundaries, and transport payloads.
At a network boundary, operations typically produce one of two mutually exclusive outcomes: a valid data payload or an error condition. In existing C#, developers frequently define these as lightweight records:
```csharp
record Success<T>(T Data);
record Error(string Message);
```
While these records represent standard, existing language constructs, they traditionally live as disconnected shapes. Dustin explains that union types serve as the declarative "glue" that binds them together into a coherent discriminated outcome: “These are old features that you're not using yet. It's fine, but with unions now I can bring these together and connect them, kind of glue them together.” This empowers APIs to return a unified result type where consumers are forced by the compiler to handle both success and failure cases exhaustively.
[09:42](https://www.youtube.com/watch?v=7qW92AwlrjM&t=582s) Modeling Generic Results and Exhaustive Switches
Dustin Campbell and Mads Torgersen pivot to exploring generic union types by modeling a classic wire protocol response: a generic `Result<T>` that encompasses two distinct cases, `Success<T>` and `Error`. Dustin begins setting up a mock scenario where data comes off the wire into a queue of results, specifically `Result<int>`. While acknowledging with a chuckle that using integers is not quite “realistic scenario territory,” they enqueue two sample cases: a successful return holding the value `42`, and an error with the message `"I couldn't type, nothing happened."`
```mermaid
flowchart TD
accTitle: Result Union Type Architecture
accDescr: Demonstrates the generic Result union branching into Success and Error cases consumed by an exhaustive pattern-matching switch.
subgraph UnionDef["Union Definition"]
R["Result<T>"]
S["Success<T> (Record)"]
E["Error (Record)"]
R --> S
R --> E
end
subgraph Consumer["Exhaustive Pattern Matching"]
Q["Queue of Result<int>"] --> W["while TryDequeue(...)"]
W --> SW{"switch (result)"}
SW -->|"case Success<int>(var d)"| D["Deconstruct & Use Data (42)"]
SW -->|"case Error(var msg)"| EX["Throw Exception"]
end
```
To process the incoming data, Dustin sets up a `while` loop that calls `TryDequeue` on the queue and dispatches the payload via a switch expression. Because the underlying cases are declared as records, the consumer can deconstruct them inline. When Dustin writes the pattern matching for `Success<int>`, the compiler immediately flags the switch expression with a diagnostic warning. Mads explains that the compiler requires exhaustion: “It's reminding us to deal with the errors, which is what you've always wanted, right?” Once Dustin handles the error case by deconstructing the error message and throwing an exception, the code runs cleanly, printing `42` before halting on the expected thrown exception.
- The union cases are modeled as records (`Success<T>` and `Error`), enabling direct positional pattern deconstruction (e.g., `case Success<int>(var d):`).
- Mads observes the irony of developer appreciation: “It's funny, right? We're in the business of giving you more errors and you love us for giving you more errors, right?”
- Union types can be generic, can define their own members, and can generally do most things other C# types can do.
- Any type can act as a case type provided it converts to `object`; case types can freely overlap, and they may be interfaces or type parameters.
- Unlike ad-hoc unions over pre-existing types, declaring case types afresh alongside the union mirrors functional programming: “We are declaring the case types afresh here together with the union type and that is sort of like that's the kind of usage that functional people would call discriminated unions that we're essentially emulating that here where you are modeling the whole package, so to speak.”
---
[13:24](https://www.youtube.com/watch?v=7qW92AwlrjM&t=804s) How the Sausage Is Made: Lowering Unions to Structs
Dustin raises the question on every systems programmer's mind: “How is the sausage made?” In standard C#, creating robust, type-safe union semantics historically demanded immense boilerplate. Mads explains that while the high-level language syntax provides an elegant veneer, the underlying mechanics can be completely exposed and manually declared. By default, the C# compiler's union syntax lowers into a very opinionated, prescriptive `struct`. To demonstrate, they comment out the concise union definition and recreate its exact lowered representation by hand using primitives available in.NET 11 Preview 4.
To instruct the compiler to treat a regular type as a union, developers decorate the struct or class with `[Union]`. Upon applying the attribute to an empty struct, the compiler immediately issues diagnostics outlining the strict protocol required to fulfill the union pattern. Specifically, a union type must expose a public instance property named `Value` of type `object`, backed by a storage field. Furthermore, it requires “union creation members”—constructors matching each valid case type. Once Dustin adds the `Value` property and individual constructors for `Success<int>` and `Error`, the compiler errors vanish one by one, producing a fully functioning manual union equivalent to the syntax-generated version.
- The compiler's syntactic union lowers by default to an internal `struct`.
- The `[Union]` attribute, introduced in.NET 11 Preview 4, instructs the Roslyn compiler to treat an explicit struct or class as a union type.
- A compliant union implementation must provide a public instance property `public object Value { get; }`.
- Case types are bound to the union by defining matching constructor overloads for each case (e.g., `public Result(Success<int> value)` and `public Result(Error value)`).
- When the compiler synthesizes unions from language syntax, it also automatically implements an interface called `IUnion` (included in.NET 11), which exposes the `Value` property for runtime type checks.
---
[17:33](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1053s) Performance Trade-offs, Custom Storage, and Legacy Interop
Mads details why the C# team designed unions as an open compiler pattern rather than a closed, opaque runtime primitive: it gives developers complete control over implementation choices. The default compiler-generated struct wraps the selected case into an `object` field, which necessarily causes boxing allocations whenever small value types (like `int` or custom structs) are placed into the union. For high-throughput scenarios, hot paths, or tight processing loops, this default boxing allocation may prove unacceptable.
By authoring the union manually, performance-minded developers can provide their own non-allocating storage layout. For instance, a union of two value types can be implemented using one field for the first type, one field for the second type, and a third discriminator tag field indicating which one is active. Mads notes that while this introduces developer complexity, it completely bypasses heap allocations (joking that “Copilot's going to write that part anyway”). Beyond performance optimization, this manual pattern solves a major backwards-compatibility challenge: developers who spent the last twenty-plus years crafting bespoke union approximations can now retrofit their existing domain models with the `[Union]` pattern and immediately gain first-class compiler enforcement and exhaustive pattern matching.
- **Default representation:** The compiler synthesizes a struct with a single `object` field, trading minimal memory footprint for heap boxing of value-type cases.
- **Custom non-boxing storage:** Developers can define an explicit struct containing separate fields for each case type plus a discriminator tag, trading struct size for zero allocations.
- **Legacy codebases:** Allows legacy classes or structs—previously guarded only by informal developer comments like `"do not derive from this class"`—to be upgraded into verified unions without breaking API surfaces.
[19:13](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1153s) Pattern-Based Unions and Internal Struct Architecture
Mads Torgersen and Dustin Campbell explain why the underlying mechanics of union types are intentionally exposed rather than locked inside compiler magic. Rather than forcing developers to discard existing custom implementations—which might feel like the C# team saying, “Nah, Alice is better”—the design allows developers to decorate their own existing types with a union attribute, declare the appropriate members, and satisfy the compiler. In doing so, existing domain types become recognized union types in the eyes of the compiler, gaining pattern exhaustiveness in switch expressions and implicit conversions for free.
Dustin points out that this approach follows a long-standing C# architectural tradition of convention and pattern-based features dating back to C# 1.0, where language constructs are built on top of recognizable signatures rather than requiring hardcoded type system primitives. While the vast majority of C# developers will never need to hand-roll custom unions, understanding the default code generation is essential when reasoning about performance. Under the hood, the default union implementation emitted by the compiler is a value-type struct containing a single internal reference-type field; values assigned to the union are stored inside that field, boxing and casting them on the way in and out. As Mads observes:
> “Now you know that it is in fact a struct with a single reference field inside that it puts whatever values they're into and boxes and casts on the way in and out.”
```mermaid
flowchart LR
accTitle: Default C# Union Internal Memory Architecture
accDescr: Diagram showing how values are assigned, boxed, and cast into an internal struct field within a union type.
subgraph InputValues["Input Values"]
V1["Value Type (e.g., int, struct)"]
V2["Reference Type (e.g., class, string)"]
end
subgraph UnionStruct["Compiler-Generated Union Struct"]
BoxOp["Boxing / Upcast"]
RefField["Single Reference Field (object / internal ref)"]
UnboxOp["Downcast / Unbox"]
end
subgraph Consumer["Pattern Matching / Switch"]
Target["Exhaustive Pattern Match"]
end
- Decorating existing custom types with a union attribute enables compiler-verified switch exhaustiveness and implicit conversions.
- Pattern-based designs keep the C# language extensible by allowing users to substitute optimized implementations where the default struct overhead is unsuitable.
- The default representation relies on a single struct wrapping a reference field, introducing boxing allocations whenever value types populate the union.
---
[21:02](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1262s) TypeScript Structural Unions vs. C# Nominal Runtime Types
The session pivots to the audience for questions, with the speakers inviting attendees to continue discussions afterward over at the "Experts Zone" located in the green developer tools pavilion. An attendee asks about the fundamental philosophical differences between C#'s approach and union types in TypeScript and JavaScript, where unions are frequently used to compensate for the lack of method overloading in inbound parameters, and requests insight into the internal design debates that shaped the C# feature.
Mads explains that the C# language design team harbored considerable envy for TypeScript's purely structural syntax, where developers can ad hoc construct arbitrary unions on the spot without formal type declarations (such as `dog | cat | bird`). The team actively explored that path, but hit an immovable wall inherent to the.NET runtime. TypeScript's type system is completely erased during compilation, meaning its union types do not exist at runtime. In.NET, however, types must remain reified entities that can be queried and inspected at runtime via reflection and type checks. As Mads articulates the fundamental divergence:
> “TypeScript has it easy because all the types in TypeScript go away at compile time; they don't exist at runtime, but if we do union types in C#, they have to mean something at runtime too.”
Because C# cannot discard type information, the language landed on nominal, declared unions rather than ad hoc structural unions. Dustin compares this compromise to how C# handles delegates: while some languages support completely anonymous function signatures, C# relies on named, declared delegates. The resulting design occupies a pragmatic middle ground between TypeScript's anonymous structural unions and functional programming's traditional discriminated unions, leaving open the door for future generic building blocks (such as a generic `Union<T1, T2>` library type) or potential syntactic layers on top.
---
[24:24](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1464s) Design Journey and Tooling Availability
Mads and Dustin conclude by reflecting on the sheer effort required to distill union types down to their final, clean syntax, noting that it required roughly five years of iteration, exploratory dead ends, and deep language design work to arrive at such a simple outcome.
Tooling support is already arriving across Microsoft's development ecosystem:
- **Visual Studio:** Support for union types is available in current preview builds targeting the upcoming.NET release.
- **VS Code:** Supported through the C# and C# Dev Kit extensions when running on the pre-release channel, with further feature parity rolling out within weeks.
- **.NET Preview:** Available to test against the upcoming preview SDKs, with the speakers encouraging the community to experiment with the feature and provide early feedback despite known preview-stage bugs.
## Notable quotes
> [21:02](https://www.youtube.com/watch?v=7qW92AwlrjM&t=1262s) TypeScript has it easy because all the types in TypeScript go away at compile time; they don't exist at runtime, but if we do union types in C#, they have to mean something at runtime too. — Mads Torgersen
## Mentioned
Mads Torgersen, Dustin Campbell, Microsoft, Microsoft Build, C#, .NET, Roslyn, TypeScript, JavaScript, Visual Studio, Visual Studio Code, C# Dev Kit, GitHub Copilot
## Video description
Union types are coming to C#! Unions model closed sets of data shapes, as commonly seen in e.g. wire protocols. Mads and Dustin explore the clean expression of intent and the confidence and elegance that unions lend to consuming code.
Seating for this session is first-come, first-served. Add it to your schedule to plan your day and arrive early to secure a spot.
To learn more, please check out these resources:
* https://aka.ms/build26/DEM304
* https://aka.ms/build26/csharp/union-types
𝗦𝗽𝗲𝗮𝗸𝗲𝗿𝘀:
* Dustin Campbell
* Mads Torgersen
𝗦𝗲𝘀𝘀𝗶𝗼𝗻 𝗜𝗻𝗳𝗼𝗿𝗺𝗮𝘁𝗶𝗼𝗻:
This is one of many sessions from the Microsoft Build 2026 event. View even more sessions on-demand and learn about Microsoft Build at https://build.microsoft.com
DEM304 | English (US) | Developer tools & frameworks
Demo | (400) Expert
#MSBuild
Chapters:
0:00 - Introduction by C# team members Mads Torgersen and Dustin Campbell
00:06:50 - Creating calculated properties and managing state
00:07:24 - Restricting unions to functional members without extra state
00:11:00 - Demonstrating exhaustive switch handling for success and error cases
00:13:56 - Explaining union type implementation using structs
00:17:54 - Performance considerations and custom union implementations
00:20:03 - Description of C# feature patterns where users can implement conventions themselves
00:20:20 - Summary of manual union writing and internal struct design for performance considerations
00:24:24 - Conclusion referencing multi-year design process and preview availability in Visual Studio and VS Code
At Microsoft Build, lead language designer Mads Torgersen and engineer Dustin Campbell introduced union types slated for C# 15, offering a pragmatic compromise between functional discriminated unions and TypeScript's structural unions. The design enforces compile-time exhaustiveness and type safety while relying on nominal runtime types and pattern-based lowering.
Type Safety and Exhaustiveness in Pattern Matching (3:28)
Historically, aggregating disparate types lacking a shared inheritance hierarchy required falling back to List<object>, which forced developers to use pattern-matching switch expressions that were vulnerable to unauthorized types and triggered compiler warnings for non-exhaustive checks. The introduction of concise syntax, such as union Pet(Dog, Cat, Bird), creates a closed set of allowable types that provides implicit conversions from valid variants while rejecting invalid types at compile time.
The compiler actively verifies exhaustive handling within pattern-matching switch expressions, eliminating non-exhaustive warnings when all variants are covered and flagging omissions immediately if a case is removed. The feature also integrates with nullable reference types, prompting compiler diagnostics if a variant signature allows null (such as Bird?) and the corresponding switch arm is absent.
Member Declarations and Real-World Wire Protocols (6:28)
Union declarations can include explicit bodies with computed properties, methods, and static members, allowing operations such as formatting descriptions to reside directly on the union type. However, the language team enforces a strict restriction against declaring additional instance state, ensuring unions serve purely as wrappers over their underlying variant values.
This structure addresses API boundaries and wire protocol results, where operations typically yield mutually exclusive outcomes such as Success<T> and Error records. Declaring generic unions like Result<T> binds previously disconnected record types together, allowing consumers to deconstruct payloads positionally while ensuring the compiler requires handling both data and error states.
Lowering to Structs and Custom Storage Trade-offs (13:24)
Syntactic unions lower by default to an internal struct decorated with the [Union] attribute, an object-typed Value property, and matching constructors for each variant case. While this default representation uses a single reference field that minimizes struct size, it incurs boxing allocations when wrapping value types, which can affect high-throughput scenarios.
To address this, C# exposes the underlying pattern, allowing performance-focused developers to hand-roll custom struct layouts featuring dedicated fields for each variant and a discriminator tag to achieve zero allocations. This pattern-based design also provides a backward-compatible upgrade path, enabling legacy classes and custom union approximations to gain compiler-enforced exhaustiveness and implicit conversions by satisfying the union pattern requirements.
Nominal Runtime Reification Versus Structural Erasure (21:02)
Unlike TypeScript, where structural union types (such as dog | cat | bird) are erased at compile time, .NET requires types to be reified entities that persist at runtime for reflection and type checks. This runtime requirement prevented C# from adopting anonymous structural unions, resulting in a nominal, declared design comparable to C#'s handling of delegates.
Torgersen and Campbell noted that this model represents the culmination of roughly five years of iteration. Preview support for testing the feature is accessible across Visual Studio, the VS Code C# Dev Kit pre-release channels, and .NET 11 preview SDKs ahead of the scheduled C# 15 release.
While the nominal struct-based design successfully brings type-safe discriminated unions and exhaustive switching into the .NET runtime, default boxing allocations on value-type variants require developers on performance-sensitive paths to manually author pattern-compliant structs.
Source quotes
[21:02] Mads Torgersen: TypeScript has it easy because all the types in TypeScript go away at compile time; they don't exist at runtime, but if we do union types in C#, they have to mean something at runtime too.
Original transcript
[0:00] Yeah.
[0:03] Lower is yours, it is ours.
[0:04] It is ours OK, but the timer is going.
[0:07] The time is going OK.
[0:09] Matt Torgeson here, lead designer of C#.
[0:16] And I'm Dustin Campbell.
[0:17] I'm an engineer also on the C# team.
[0:21] And we do C#.
[0:22] We do C#.
[0:23] And today we'll talk about just one tiny little feature
[0:25] that we're adding to C# called Unions.
[0:28] Union Types.
[0:29] C# 15.
[0:30] C# 15, it's coming out November.
[0:34] Stuff is already in preview.
[0:35] We can talk a little bit at at the end
[0:37] about how to try it.
[0:40] Unions is a thing that other languages have.
[0:44] TypeScript has unions.
[0:46] Most functional programming languages have some sort of discriminated unions,
[0:50] and they're all different.
[0:51] And we're now adding unions to C# and they're different
[0:54] again.
[0:55] They're our own little we call it Goldilocks, but you
[0:58] can also call it compromise version of it.
[1:01] So if you know unions already, this will be different.
[1:05] If you don't, you don't have to worry about it
[1:06] because we're just going to show you how unions should
[1:09] be.
[1:11] And as this is a demo session, there's your slide
[1:15] moving over to demo.
[1:16] OK, so we have code here, right?
[1:20] And it's a, it's some modern C# code with top
[1:23] level statements.
[1:25] And what it is, we've got a series of records
[1:28] down here.
[1:29] Well, not all records, just a bunch of types that
[1:32] represent pets or animals, right?
[1:34] Animals like animals.
[1:35] And let's imagine they're not really here like in the
[1:37] real world scenario.
[1:38] They're just types all around.
[1:39] There's a dog library.
[1:40] There's a cat library.
[1:41] Yeah, but they don't talk to each other because dog
[1:44] and cat people and yeah.
[1:45] And we want to talk about pets.
[1:47] Pets, right?
[1:48] So up here we have if we want to talk
[1:50] about pets, we have to they don't really have anything
[1:53] in common these types, right?
[1:55] So the best we can do is go all the
[1:57] way to the top and go, well, we have to
[1:59] treat them all as object, right?
[2:01] So we have a list of object of pets, right?
[2:03] And then we for each over these pets, we produce
[2:06] it as we got a switch expression over each pet
[2:09] to kind of deconstruct those values out and turn them
[2:12] into a description.
[2:13] And then we write to the console, OK, and this
[2:17] will in fact demonstrate that there are 4 pets in
[2:22] this.
[2:23] Right, the four somethings.
[2:25] Yeah, and one of them is not what I would
[2:28] consider a pet.
[2:30] OK, we're in San Francisco, so hey, to each his
[2:32] own.
[2:33] But maybe sharks or pets here in San?
[2:35] Francisco not with that many teeth, but yeah, so we
[2:38] have in here, we have a shark as well.
[2:40] And so they there's no type safety, right?
[2:43] You want a certain set of types, but there's no
[2:46] way to protect against the other ones either in when
[2:49] you're constructing that list or when we're switching against them
[2:53] after.
[2:53] And you can actually also see there's a little squiggle
[2:56] on the switch there saying and you are not checking
[2:58] all the other things an object could be, You're not
[3:01] checking for crocodiles and so on.
[3:02] Go down the list.
[3:03] Yeah, I mean all the other natural pets like crocodiles
[3:06] and snails.
[3:06] So there's really, yeah, Keep, Yeah, like we only have
[3:09] 25 minutes, I guess.
[3:11] But yeah, so, so this is not great, but this
[3:14] is sort of the best we can do in C#
[3:16] up until now.
[3:17] Yeah.
[3:18] But wouldn't it be nice if even they, even though
[3:21] these types were not created in a context where there
[3:23] was a notion of pet, why can't we create a
[3:25] notion of pet that they can belong to?
[3:28] And that's what union types are in C#.
[3:30] Right.
[3:30] And so we create them with just typing union and
[3:33] then we can say we're creating a union of pets
[3:37] and I can just put the different types that make
[3:40] up that set of that thing, that set of types
[3:43] that is pet.
[3:45] OK.
[3:45] And it's that simple, right?
[3:47] Then I can take pet and I don't have to
[3:50] talk to these as object anymore.
[3:51] I can say, well, no, this is a list of
[3:53] pet.
[3:54] And now we get an error because shark not a
[3:58] pet shark saying and.
[4:00] It says, if you look at the error there, it
[4:03] says cannot implicitly convert type shark to pet.
[4:06] So that's good.
[4:07] But and that says something important and we can, it
[4:10] means we should go and delete that line.
[4:12] But what it also says is that you can implicitly
[4:15] convert the other types to heads.
[4:18] So one of the things that a union type apparently
[4:21] can do in C# is you can convert from the
[4:24] case types, the things in the list down there to
[4:27] the union type.
[4:28] That makes sense, right?
[4:29] So OK, implicit conversions, right?
[4:32] Check.
[4:33] And then as we come down, we're doing our pattern
[4:36] matching here.
[4:36] It's our switch expression.
[4:38] And then and then, you know, decomposing each of these
[4:40] shark again has the error.
[4:42] Hey, look, it can't you know, expression of type pet
[4:44] cannot be handled by a pattern of type shark.
[4:47] It.
[4:47] Yeah, not a pet.
[4:49] Doesn't.
[4:49] Match so we can take rid of this.
[4:50] But what's really cool here is that warning that was
[4:53] on the switch that said that it was not, could
[4:56] not be proven to be exhaustive.
[4:58] It is now we've covered all the cases, right?
[5:02] Everything that's a pet is covered by the switch.
[5:04] And we now get compiler support.
[5:06] We get compiler help to let us know that yes,
[5:08] we have correctly handled everything.
[5:10] Yeah, and to prove the point, let's comment out one
[5:13] of the actual case types.
[5:15] Yeah, we get that back.
[5:15] Right, so you get the warning back.
[5:18] So it's really helping you make sure you hit all
[5:20] the cases and nothing but the cases.
[5:22] That's part of the strong typing you get here.
[5:26] Yeah.
[5:26] And it's smart, right?
[5:27] Like you could actually have like we could say pet
[5:30] is actually a union of dog and cat and maybe
[5:32] a bird, right?
[5:33] So you could say it's like a nullable bird.
[5:35] And now again, the warnings back because now that null
[5:38] should be handled as well as one of the possible
[5:40] cases.
[5:40] So it's now not exhaustive.
[5:41] So it's very smart around these kinds of things.
[5:44] It's cool.
[5:45] That's the feature.
[5:46] Yeah.
[5:47] Thank you very much and have a good have a
[5:49] good conference.
[5:50] It is.
[5:50] It's the feature.
[5:51] So, so, so far is this.
[5:53] Do you like it?
[5:53] It's OK, yeah.
[5:55] Some nodding.
[5:56] OK.
[5:56] Yeah, yeah, I guess.
[5:57] Smiling.
[5:58] Yeah.
[5:58] OK.
[5:59] Thank you.
[6:01] I, I we should do more crowd.
[6:02] Work, I feel like one of the things we get,
[6:05] we get a lot of feedback that we always do
[6:07] these demos that are like a a domain of like
[6:10] something like not really like the code you're trying to
[6:13] write.
[6:14] Like we're always doing person and student and here we're
[6:17] doing pets and dogs and cats and birds.
[6:20] We should probably try something that is more in that
[6:23] domain.
[6:24] Let's do.
[6:25] The Let's Show Do we want to show members on?
[6:28] Oh yeah.
[6:29] We should do that first.
[6:29] Actually, I want to do show one more thing here
[6:33] now before we dig into that union itself.
[6:36] Like it's a very, very short description, but of course,
[6:38] you know, you could actually write a class or instruct
[6:40] that way.
[6:41] It's just not very useful.
[6:42] What we usually do, right is we put braces on
[6:44] it and then you declare members, right?
[6:47] So we can declare a member in here.
[6:48] We can actually declare this whole description thing.
[6:51] This whole description calculation could just copy down here and
[6:55] we could say, well, let's make this like a public
[6:59] property, strict, not strict.
[7:01] We don't even.
[7:02] That's C#.
[7:02] We don't even have.
[7:03] That in that world, yeah.
[7:05] And we can make it like, you know, a calculated
[7:08] property.
[7:08] But I can't switch on pet anymore.
[7:11] I mean, I have to switch on this.
[7:12] What kind of pet is this right now?
[7:15] So now I can switch on that and then we
[7:17] can come up here and we can just get rid
[7:20] of that.
[7:22] Yeah, just say pet the description.
[7:23] Yeah.
[7:24] So, so you can add your own function members to
[7:26] it that compute stuff or whatever.
[7:28] We we do draw a line at things that introduce
[7:31] more state because we think you should think of it
[7:34] as the state of this thing is just the actual
[7:37] dog or cattle bird that's inside it shouldn't have additional
[7:41] state, right that.
[7:42] So we we prevent you from that.
[7:44] But as long as it's just a function member, a
[7:46] computer property, method, whatever, whatever static members you want, that's
[7:50] totally fine.
[7:51] So you can still do abstraction here and and the
[7:54] kind, some of the common things you want to do
[7:56] across the types in this concept you just created implement
[8:00] them there.
[8:01] OK, so that's that's how that's pretty much how I
[8:04] think most people will use the feature.
[8:06] I hope so.
[8:06] I hope this is useful.
[8:07] Yeah.
[8:09] Because it is really great for collecting together these things.
[8:11] And I was kind of alluding trying to head there
[8:13] just a second ago.
[8:13] Yeah, right.
[8:14] I'd like, we'd like to just show you again, but
[8:17] like kind of in a in a domain that's like
[8:19] closer to what?
[8:20] Like maybe you might be using this in normal code
[8:22] that isn't all about cats and dogs.
[8:23] That is about in fact one of the things that
[8:26] almost everyone who asked us to add unions to C#
[8:28] been asking about, specifically at the.
[8:31] Scenario.
[8:31] So let's go there.
[8:32] What you see here is like.
[8:34] This is nothing right now, sorry.
[8:36] You want to go back?
[8:37] No.
[8:37] And it's good.
[8:38] It's good.
[8:38] OK, let's start over.
[8:40] So let's do another, let's do a slightly different kind
[8:43] of union scenario here.
[8:45] Yeah.
[8:46] So stuff on the wire, you get something back on
[8:50] the wire, either there's something or maybe you get an
[8:55] error, right so.
[8:57] There's like you get like a success, right?
[9:01] You get back, you're going to model that data as
[9:04] like you get a success and that could be like
[9:06] anything in there.
[9:07] Yeah, it has some kind of payload.
[9:08] So put in like, yeah, data T, yeah, make that
[9:11] generic.
[9:12] That's what you want, that's what you want.
[9:13] What you get is.
[9:14] Yeah, and and an error.
[9:16] And then you want an error or you get an
[9:18] error.
[9:18] So you need to model this as well, right?
[9:20] So we'd say it could be one of these two
[9:22] things, right?
[9:24] And then we can come in here.
[9:25] Yeah, these are just records that are in the language
[9:27] today, right?
[9:28] Yeah, you can just write these already.
[9:29] These are not new features.
[9:30] These are old features that you're not using yet.
[9:33] It's fine, but with unions now I can bring these
[9:36] together and connect them, kind of glue them together.
[9:39] So the compiler knows if these are related things, right?
[9:42] And I can use those generics within it, right?
[9:45] So I can say, you know, let's say we'll call
[9:48] this like result, OK.
[9:50] And that has two cases, right?
[9:52] It has success of T and it has error and
[9:55] now I could have a method that returns result of
[9:58] T and it can return one of these two things.
[10:00] Yeah, you.
[10:01] Make it sound so cool I.
[10:02] I do try to make it sound cool, actually.
[10:06] Let's put together some data that we can kind of
[10:08] model this.
[10:08] Like I'm getting stuff off the wire, right?
[10:11] So we'll say like, we'll make a queue of of
[10:13] like results of say like like we're getting ints off
[10:16] the wire.
[10:17] Yeah, we're not heading totally into like realistic scenario territory
[10:20] here.
[10:20] We still got to have ints inside.
[10:22] But like, it's the stuff where we're like, well, let's
[10:25] in queue a couple of things that come from like,
[10:27] you know, the data, we'll say we we want to
[10:29] get a, let's get a success, say like, yeah, 42's
[10:32] returned, that'd be successful.
[10:35] And then like a new error like the error that
[10:39] I couldn't type, nothing happened.
[10:43] That's a good error.
[10:44] Yeah, sorry.
[10:46] Yeah.
[10:46] OK.
[10:47] So we've got some results and then we went to
[10:49] like loop over these results.
[10:50] So I could like do a while loop and you
[10:53] know in there we could try and dequeue and grab
[10:56] out the result and then come down in here.
[10:59] And do a switch.
[11:00] Again and do a switch to get that data out.
[11:02] So switching on result.
[11:03] So say switch and what's the first switch going to
[11:09] be?
[11:09] It's going to be a.
[11:10] Success, right?
[11:10] Yeah.
[11:10] So assuming it's a success of int of int.
[11:14] But now we can deconstruct it.
[11:15] Because it's a record, yeah.
[11:17] Which is.
[11:18] That's why you should use records.
[11:19] See.
[11:19] You can deconstruct the data right out of it.
[11:21] Yeah, and.
[11:22] I can just pull out the D, right?
[11:24] Pull out that data and then down here we're going.
[11:26] To do notice.
[11:27] Yeah.
[11:28] Oh, and now I have the.
[11:29] Switch on the switch.
[11:30] Because I haven't.
[11:31] You haven't.
[11:32] Dealt with the errors.
[11:33] So it's reminding us to deal with the errors, which
[11:35] is what you've always wanted, right?
[11:36] Yeah.
[11:38] OK, so let's go ahead and do that.
[11:39] We'll grab out that message and you know, we'll just
[11:43] throw it.
[11:44] Throw it, fine, bad things happen.
[11:46] Sorry.
[11:47] And I think that's what do we want to do.
[11:50] No, we should write it.
[11:51] We should write the like, you know, do.
[11:52] It like write it and.
[11:54] Then we should run it.
[11:55] OK, let's make sure Dustin typed everything right.
[12:01] There you go.
[12:01] Gets 42, throws the exception.
[12:04] And so, yeah, we're really in the business.
[12:06] It's funny, right?
[12:06] We're in the business of giving you more errors and
[12:09] you and you love us for giving us more, for
[12:11] giving you more errors, right.
[12:13] It's like because you're getting a a tighter control of
[12:16] your scenario here again.
[12:17] Yeah, One thing I so now you've seen this union
[12:21] type can be generic.
[12:23] They can so we they can have members, they can
[12:24] be generic.
[12:25] They can do most things that other types can do.
[12:28] The the case types themselves can be most things as
[12:30] long as they can, as long as they convert to
[12:33] object, they can be case types.
[12:34] It's fine if they overlap or whatever.
[12:36] There's no like restrictions on that.
[12:37] They can be interfaces or type parameters or whatever.
[12:40] So it's a pretty general feature.
[12:42] But I wanted, I want you just to call out
[12:44] this scenario is subtly different than the one we had
[12:47] before in that it's not working on existing types that
[12:50] were already in the system.
[12:51] It's not trying to bring stuff together that others declared
[12:54] it.
[12:55] We are declaring the case types afresh here together with
[12:59] the union type and that is sort of like that's
[13:02] the kind of usage that functional people would call discriminated
[13:06] unions that we're essentially emulating that here where you are,
[13:10] where the you are modeling the whole package, so to
[13:13] speak.
[13:14] You're modeling the kinds of thing, things it can be
[13:17] and the union saying that it can be those kinds
[13:20] together.
[13:21] And and I think that's going to be a common
[13:23] pattern of usage as well.
[13:24] Yeah, well, and one thing that stuck with me.
[13:28] So I love this.
[13:29] I think it's cool.
[13:30] I think I will find it useful.
[13:32] OK, but how is the sausage made?
[13:36] Yeah, what's under the hood, Right.
[13:38] What's actually happening here?
[13:39] Because it seems like, I mean, if you work with
[13:42] T sharp type systems, this feels kind of magical in
[13:45] a way.
[13:45] If you've ever tried to write this sort of thing,
[13:47] it requires a lot of boilerplate.
[13:49] So what are we doing here?
[13:51] It's actually.
[13:53] So it's actually in some ways fairly simple.
[13:56] Well, then the feature is there's a whole like language
[13:59] feature on top.
[14:00] But you, if you're wondering what's underneath, what is that
[14:03] union actually in terms that you you already have today.
[14:06] We can actually show you.
[14:07] We can, we can comment that out and we can
[14:10] write it in a long form instead.
[14:12] That actually also works.
[14:14] Yeah, because unions, under the hood, there's they're they're structs.
[14:18] When we create them, we give you kind of a,
[14:22] a very, very like like prescriptive form, very opinionated form
[14:26] of what a union should be.
[14:28] When we produce 1 and what that prescription is, it's
[14:31] like we're going to create a struct, right?
[14:35] And that struct, what's that?
[14:37] Yeah, we want to tell the compiler so.
[14:41] So what are we saying here is you can build
[14:43] your own union types that are different from what we
[14:46] produce from the syntax.
[14:47] And it's just, it just takes a little more work,
[14:50] but not that much.
[14:51] So we're going to use that little more work to
[14:53] actually produce exactly the same thing.
[14:54] But you could have done made different choices.
[14:57] You have to tell the compiler, hey, I know this
[14:59] is just a struct or a class or whatever, but
[15:02] I mean for it to be a union.
[15:04] So we do that by putting an attribute on it.
[15:06] It's really complicated attribute.
[15:08] It's already in.net 11 Preview 4.
[15:12] There is a union attribute that makes us work with
[15:16] five errors.
[15:17] Actually more than that, there's more.
[15:18] There's two errors on the spot.
[15:20] And these are just errors.
[15:21] The compilers giving you to say like this doesn't work,
[15:23] right?
[15:24] Because you're saying this is a result, but nothing connects
[15:26] success and error with this any anymore because we've commented
[15:29] that down below.
[15:30] So we need to do that, right?
[15:32] First of all, the very bottom warning or error says,
[15:35] hey, a union member like it must have have a
[15:38] public instance, right?
[15:40] Like if if this is a, this is a union,
[15:42] it must have a public instance value property of type
[15:45] object.
[15:45] And that's actually something that I didn't poke into up
[15:48] here, but when we just had the union earlier, if
[15:51] I dotted into that, you'd see that value property, right?
[15:54] So we need to have one too.
[15:56] And it looks really complicated.
[15:59] No.
[16:00] It's like that.
[16:01] OK, and that gets rid of one of those errors.
[16:04] So that's just a oh, and you're hiding it right
[16:06] now I'm hiding it.
[16:07] But that's just an auto property.
[16:09] It's just it has a field behind it of type
[16:11] object that contains whatever it is that this union actually
[16:14] is now wrapped in this struct.
[16:16] But let's get rid of these other errors up here.
[16:18] Yeah, let's start.
[16:19] How would it connect success and error?
[16:22] Well, it says it needs at least one union creation
[16:25] member.
[16:25] How do you create things?
[16:27] Constructors.
[16:28] Constructors.
[16:28] Right.
[16:28] So we'll add a constructor to this type that takes
[16:32] first one will take a success of int.
[16:35] We'll call that parameter, we'll call it value.
[16:37] And then we'll just kind of assign the, we'll assign
[16:40] the big value property to the little value down there.
[16:44] And if you look, you see that the success errors
[16:47] went away, Yes.
[16:48] And now we just have one on.
[16:49] Error and the error on the result went away as
[16:52] well because now it does have one case type.
[16:55] So now it's a union of one thing.
[16:57] And we just need to add the other, right?
[16:59] Just another constructive for each case type.
[17:01] Yeah.
[17:01] And so we'll just add.
[17:02] Error in here and.
[17:04] Now we have a Union.
[17:05] You need to go now.
[17:06] We've constructed everything the compiler is going to look for
[17:09] in treating this as a union.
[17:11] Yeah, we do add one more thing when we generate
[17:13] from the syntax, which is it implements an interface called
[17:16] I union.
[17:17] It's also already in.net 11.
[17:19] And which just says it has the value property that's.
[17:22] All it does is all it does is have the
[17:23] value property.
[17:24] So if you want to check for unions or you
[17:26] know to do a runtime check and call that and
[17:28] and some just like generic runtime code you can so.
[17:31] Yeah, but so why are we doing this?
[17:33] Why are we letting you do it this way as
[17:34] well?
[17:35] It is so that you can make other implementation choices
[17:37] for your union.
[17:38] If you don't like our our default that our syntax
[17:42] generates that takes whatever case types and boxes them into
[17:46] an object field and so on, then they're kind of
[17:49] two major reasons why you might want a different implementation.
[17:54] 1 is you are like really performance, you know, in
[17:58] a very sort of tight loop or whatever, really performance
[18:03] aware.
[18:04] And you have, you want a union of two little
[18:06] value types and you don't like that they get boxed
[18:08] every time you create a union value from that's an
[18:10] allocation that's expensive, whatever.
[18:12] Well, choose your own form of storage.
[18:14] Like have a field of the one type of field
[18:16] of the other type and a third field that says
[18:18] which one of them that is inside.
[18:20] And you can avoid the boxing.
[18:21] And there are extra things we're not going to show
[18:23] you.
[18:23] You can have the compiler generate different code and usage
[18:27] that also avoids the box.
[18:28] So the ways that you can make it non boxing
[18:31] at at significant expense like it's going to be more
[18:34] complicated from a like a developer point of view.
[18:38] But if you want to save, save those extra allocations
[18:42] or whatever, that's a way to do it.
[18:44] And Copilot's going to write that part anyway, so that's
[18:46] fine.
[18:47] Yeah, right.
[18:47] As long as you all teach it.
[18:49] Yeah, it'll be fine.
[18:51] So that is.
[18:52] That's one scenario, yeah.
[18:53] And the other one is, hey, we had we haven't
[18:56] had unions for 20 some years in C#.
[18:59] And so you did your best to write your own
[19:01] union types.
[19:01] Some of you, you have your own things that represent
[19:04] unions.
[19:04] You're like comment, do not derive from this class or
[19:08] comment, do not assign any other types to you know,
[19:11] you're trying your best.
[19:13] And now here we are with a brand new language
[19:14] feature and we're stomping all over you and saying, Nah,
[19:17] Alice is better.
[19:18] So instead you can put that union attribute on your
[19:21] existing types that you want to be unions and maybe
[19:25] add a few more members and stuff to make the
[19:27] compiler happy.
[19:29] And now your existing type can also become a union.
[19:31] Types in the eyes of C# in the eyes of
[19:34] the compiler can get that exhaustiveness in the switch and
[19:38] the implicit conversions and all of that for free.
[19:42] So that is, those are the reasons why the underpinnings
[19:46] of the syntax itself are exposed for you to to
[19:49] do whichever way you like, yeah.
[19:52] It's sort of like, I mean, there's a lot of
[19:54] features in C really starting with, I mean starting from
[19:57] the beginning.
[19:58] But we've had a lot of features that like that
[20:01] are built on patterns, right?
[20:03] Things convention that we put in that you can go
[20:06] and implement yourself.
[20:07] They're not necessarily.
[20:09] You know, in the type system per SE, but the
[20:11] compiler will triple them specially, right?
[20:13] And so that's what we've done with unions.
[20:15] And this is just kind of like the basics and
[20:17] you can go deep, you can go far, and it's
[20:19] pretty cool.
[20:20] And most of you will never need to do this
[20:23] manual union writing stuff, but it's probably good for you
[20:26] to see how our default one what that looks like
[20:28] inside.
[20:29] Now you know that it is in fact a struct
[20:31] with a single reference field inside that it, that it
[20:34] puts the whatever values they're into and boxes and casts
[20:38] on the way in and out.
[20:40] Good to know for like when you're thinking about performance
[20:43] or whatnot.
[20:44] So that's pretty much it for the.
[20:50] Unions in C#?
[20:51] Unions in C#, Yeah, that we would love to take
[20:54] questions, but we'll probably only like get to 1 and
[20:59] then we have a final slide we'll say.
[21:02] Exhaustive.
[21:02] It's huge.
[21:03] Yeah, but we before we do the questions like I
[21:06] know more, more of you might want to talk to
[21:09] us about it.
[21:10] We'll try to sneak away far enough that we're not
[21:14] upsetting the next session here when we're done, and then
[21:17] we will do our best to make it over to
[21:20] the experts zone over the.
[21:22] Pavilion over there the.
[21:23] Pavilion over there, that's the green dev tools area.
[21:27] That's like a big cube.
[21:28] We'll be hanging over here.
[21:29] We'll try to be there.
[21:31] So come talk to us about unions there.
[21:32] OK.
[21:33] All right.
[21:34] Let's take the question though.
[21:35] Yeah.
[21:52] Excellent.
[21:53] You're gonna have to say it again, but you got
[21:54] to.
[21:54] You have to practice and.
[21:55] That's OK, Fantastic case.
[21:57] I'll even stand up for you.
[21:58] So can you.
[21:59] Obviously this exists in TypeScript JavaScript, which is probably what
[22:02] many people are familiar with, and it's used kind of
[22:04] in a different way.
[22:05] A lot of times because it doesn't support overloads, you
[22:07] end up using that with inbound parameters and things like
[22:10] that.
[22:11] I'm sure you had tons of discussion about how this
[22:14] should be done here.
[22:15] Can you just like expose us to a little bit
[22:17] of that internal dialogue from your team?
[22:19] Yeah, we'll do so.
[22:21] So in TypeScript, union types are they're kind of structural.
[22:26] You don't have to declare them by name.
[22:27] You can just sort of cook them up on the
[22:29] spot.
[22:29] Like, you know, you can say dog or cat or
[22:31] bird and like it just in as a type of
[22:33] something and it'll figure it out.
[22:36] And we were really like, we had some envy of
[22:38] that.
[22:39] Took a stab at it I think.
[22:41] Yeah, we tried designing down that, down that path, but
[22:45] what we found was TypeScript has it easy because all
[22:49] the types in TypeScript go away at compile time.
[22:53] They don't exist at runtime.
[22:54] Types don't have to exist at runtime.
[22:56] But if we do union types in C#, they have
[22:58] to mean something at runtime too.
[23:00] You have to be able to, to ask questions about
[23:03] them at runtime.
[23:05] That's just how.net works.
[23:07] So we can't just throw them away.
[23:08] And for that, it's better to have types at the
[23:11] end of the day, it's just better to have types
[23:13] that you then declare and give a name like if
[23:15] you want, you can create a, a library and maybe
[23:18] we will one day that is union of T, union
[23:20] of T1, T2 and so on that you can kind
[23:22] of get some of that structuralness back with generics.
[23:25] We haven't done that yet, but that's a, that's a
[23:27] possibility.
[23:27] So we kind of had to, we like the TypeScript
[23:30] is a, is unions of types.
[23:32] They are type unions and we took that, but these
[23:36] are, these are like nominal declared unions of types.
[23:39] We couldn't do the other thing we made.
[23:42] I think we may come back to it.
[23:43] We.
[23:44] May come back to it at some point.
[23:45] There might be a layer on top of this or
[23:46] something.
[23:47] That's their proposals.
[23:48] But for now, the compromise is this is more like
[23:52] delegates that you know some some languages have function types.
[23:57] We don't have anonymous function types, but we have ways
[24:00] you can declare.
[24:01] Them and and in a functional programming language where you
[24:04] have discriminated unions, that's very different, right, Where everything's nominal
[24:08] than that.
[24:08] And so this is kind of like going right in
[24:10] the middle and trying to say like, can we do
[24:12] kind of both?
[24:13] Yeah.
[24:14] And now we're right.
[24:15] So let's put that slide up.
[24:16] But now you've got a taste of what will happen
[24:18] if you ask us a question after.
[24:20] Yeah.
[24:21] So we're going to, we're going to do something like
[24:23] that.
[24:24] We, it took us five years roughly to get to
[24:27] this very simple design.
[24:29] So we, we went down a lot of paths and
[24:31] we were happy to talk about it at length here,
[24:33] though just a few resources.
[24:36] The preview of Visual Studio for instance that's out has
[24:41] support for uniontypesthe.net 11 preview VS Code, especially if you
[24:48] run the C# extension in pre.
[24:50] And the insiders are pre release.
[24:52] Extension, Yeah, it will get what we showed will be
[24:54] there in about a couple of weeks, I think, so
[24:57] it will get even better.
[24:58] There's some bugs in there, but that's it.
[24:59] So go try it.
[25:00] Thank you for listening.
[25:01] Come ask questions.
[25:03] See you all later.
[25:04] Hope you like it.
[25:04] Yeah.