
C# 15 makes discriminated unions part of the language. A single line such as public union ImportRow(Reading, EmptyLine, InvalidReading); declares a closed set of alternatives, and the compiler checks that every switch expression handles all of them. Until now, that capability required a library. Unio
is one such library, an open source project that I maintain, built around a generic readonly struct with typed storage for each case. Its design is described in Unio: High-Performance Discriminated Unions for C#
, and the language proposal behind C# 15 unions in C# 15 Unions: Unions are finally in .NET
.
With .NET 11 released, the obvious question is whether such a library still has a place. The answer depends less on syntax than on four properties of the code that uses the union: where the values are stored, what an unassigned value means, which subset of cases crosses a method boundary, and which runtimes have to share the same types. This article examines those four properties using a single example, measures the parts that can be measured, and ends with a decision guide.
Versions: .NET SDK 11.0.100 with C# 15, Unio 2.0.7, BenchmarkDotNet 0.16.0-preview.2. All measurements on .NET 11.0.0 (x64) with an AMD Ryzen 9 9950X under Windows 10 22H2. Every code sample in this article compiles with these versions; compiler messages are quoted verbatim.
The example: a temperature importer
A temperature importer reads a file with one value per line and produces one result per row. Most rows contain a valid reading. Some are blank, and occasionally a sensor writes something like OFFLINE into the temperature column. All three outcomes are expected, so none of them is an exception. Each case carries exactly the information its consumer needs:
1public readonly record struct Reading(double Celsius);
2public readonly record struct EmptyLine(int LineNumber);
3public sealed record InvalidReading(int LineNumber, string Input);A valid reading contains a number. A blank row carries its position in the file. An invalid reading also preserves the original input for diagnostics, which is why it is a reference type: it holds a string anyway.
Two variations of the importer matter for the rest of the article. The streaming variant parses a row and handles it immediately. The buffered variant parses a whole batch of, say, a million rows into an array before processing it, for example to validate the batch as a unit or to hand it to another component. The union type is the same in both cases; its costs are not.
How C# 15 unions work
The native declaration is short:
public union ImportRow(Reading, EmptyLine, InvalidReading);The compiler turns this declaration into a struct marked with [System.Runtime.CompilerServices.Union] that implements IUnion. It generates one public constructor per case type and a Value property of type object? that returns the stored case. Each case type converts implicitly to the union, so a parser can return a case value directly from a method declared to return ImportRow:
1public static ImportRow ParseRow(int lineNumber, string text)
2{
3 if (string.IsNullOrWhiteSpace(text))
4 {
5 return new EmptyLine(lineNumber);
6 }
7
8 if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out double celsius))
9 {
10 return new Reading(celsius);
11 }
12
13 return new InvalidReading(lineNumber, text);
14}On the consuming side, type patterns test the contents of the union rather than the union instance. row is Reading reading succeeds when the stored value is a Reading, and a switch expression can list the case types directly:
1public static int CountSamples(ImportRow row) => row switch
2{
3 Reading => 1,
4 EmptyLine => 0,
5 InvalidReading => 0
6};The union itself adds no custom equality, formatting or deconstruction. It answers one question, “which case is it?”, and leaves the data to the case types. The union type reference describes the full set of rules.
How Unio works
Unio takes a different route to the same goal. Unio<T0, T1, T2> is a generic readonly struct with a one-byte discriminator and one typed field per case. No declaration is needed; the type can be used ad hoc in a method signature:
public static Unio<Reading, EmptyLine, InvalidReading> ParseRow(int lineNumber, string text)Implicit conversions work the same way as with the native union, so the method body is identical. Consumption uses methods instead of language patterns: Match and Switch take one delegate per case and enforce completeness through their parameter lists, TryGetT0 extracts a specific case, and TryPickT0 extracts a case and returns the remaining ones as a smaller union. Unio also generates structural equality and formatting, and an optional source generator creates named union classes. The API reference
lists all members.
Both approaches give compile-time guarantees, but they express them differently: the native union through the language’s pattern matching, Unio through its method signatures. The following sections show where that difference becomes relevant.
Exhaustiveness, and the value nobody assigned
Suppose the file format gains support for comment lines. Adding CommentLine to the union declaration produces a warning at every switch expression that does not handle it yet:
1warning CS8509: The switch expression does not handle all possible values of its input type
2(it is not exhaustive). For example, the pattern 'CommentLine' is not covered.That warning is the main benefit of a closed set of cases, and it is worth protecting. A catch-all arm such as _ => 0 would silence it and silently decide how every future row type contributes to the summary. Two details limit the guarantee. It applies to switch expressions only; a switch statement over the same union compiled without any warning in the same experiment. And it is a warning, not an error. Only TreatWarningsAsErrors, or at least <WarningsAsErrors>CS8509</WarningsAsErrors>, turns the hint into a rule that a build cannot ignore.
A further gap concerns values that were never assigned. The default value of a generated union contains null. That is not an exotic edge case in the buffered importer, because every element of a freshly allocated ImportRow[] starts out as a default value. Since all three case types are non-nullable, the compiler does not ask for a null arm, and CountSamples throws a SwitchExpressionException when it receives such an element. The documentation recommends an explicit null arm whenever default values can reach a switch:
1public static int CountSamples(ImportRow row) => row switch
2{
3 Reading => 1,
4 EmptyLine => 0,
5 InvalidReading => 0,
6 null => 0
7};Unlike a discard, the null arm keeps the exhaustiveness check intact: with CommentLine added, this version still produced CS8509.
Unio behaves differently here, and the difference deserves a clear statement. A default Unio<Reading, EmptyLine, InvalidReading> reports Index == 0 and IsT0 == true. It is indistinguishable from a real Reading with 0 °C. The native union fails loudly on an unassigned slot; Unio silently produces a plausible temperature. For a buffer, that means either filling every element before reading it, tracking the number of written elements, or choosing a first type argument whose default value is harmless. Neither behavior is wrong, but they fail in very different ways.
Where the values live
The storage strategy is the most technical difference and the one most often reduced to a slogan. The native union stores its contents in a single object? field. Reference-type cases such as InvalidReading are stored as they are. Value-type cases such as Reading are boxed: converting new Reading(21.5) to ImportRow allocates a small heap object that holds the double. Unio stores each case in its own typed field, so a Reading is copied into the struct without any allocation.
The sizes of the types show the other side of that trade-off:
| Type | Size of one value |
|---|---|
ImportRow (C# 15 union) | 8 B |
Unio<Reading, EmptyLine, InvalidReading> | 32 B |
Unio<EmptyLine, InvalidReading> | 16 B |
Custom [Union] struct (shown later) | 24 B |
The native union is always the size of one reference, regardless of how many cases it has. A Unio value reserves space for every case plus the discriminator, including the cases that are not active.
For the buffered importer, both effects meet. The following numbers were measured with GC.GetAllocatedBytesForCurrentThread() while filling an array with one million rows, of which 98 % are valid readings, 1 % blank lines and 1 % invalid readings. The InvalidReading instance was shared so that only the storage of the union itself is counted:
| Variant | Allocated for 1,000,000 rows | Heap objects |
|---|---|---|
| C# 15 union | 31,760,024 B | 990,001 |
| Unio | 32,000,024 B | 1 |
Custom [Union] struct | 24,000,024 B | 1 |
The native union allocates an 8 MB array of references plus 990,000 boxes of 24 bytes each, one for every Reading and every EmptyLine. Unio allocates a single 32 MB array. The total is almost identical. What differs is the number of objects: almost a million small objects that the garbage collector has to trace, and that are promoted to older generations if the batch lives long enough, versus one large array.
Reading the values back allocates nothing in any of the three variants. row is Reading reading unboxes the native union, and TryGetT0 copies the value out of Unio’s typed field. One Unio member is an exception: its Value property returns object and boxes value-type cases again. Iterating the million rows with row.Value is Reading allocated 23,760,000 bytes, exactly the boxes the typed storage was meant to avoid.
Two conclusions follow. If all case types are reference types, the boxing argument disappears entirely, and the native union is simply smaller. And if a rare case is represented by a large struct, Unio makes every element of the buffer larger, including the common ones.
Measuring construction and consumption together
Allocation counts alone do not answer the question of throughput. A meaningful benchmark has to include both the construction of the rows and their consumption, because the costs are distributed differently: the native union pays when the boxes are created, Unio pays when a wider array is written and read. A benchmark that repeatedly matches an already constructed value measures neither.
The benchmark for this article models both importer variants with BenchmarkDotNet. A precomputed array decides the case of each row, 98 % of the rows are readings, and each parser method is marked NoInlining to represent a real method boundary. The buffered variant allocates a new array per batch, fills it and then sums all valid temperatures:
1[MemoryDiagnoser]
2public class ImportBatchBenchmarks
3{
4 [Params(10_000, 1_000_000)]
5 public int RowCount;
6
7 private byte[] _kinds = [];
8 private InvalidReading _invalid = new InvalidReading(0, "OFFLINE");
9
10 [MethodImpl(MethodImplOptions.NoInlining)]
11 private ImportRow ParseNative(int i) => _kinds[i] switch
12 {
13 0 => new Reading(15 + (i & 15) * 0.5),
14 1 => new EmptyLine(i),
15 _ => _invalid
16 };
17
18 [Benchmark(Baseline = true)]
19 public double NativeUnion_Buffered()
20 {
21 ImportRow[] rows = new ImportRow[RowCount];
22 for (int i = 0; i < rows.Length; i++)
23 {
24 rows[i] = ParseNative(i);
25 }
26
27 double sum = 0;
28 foreach (ImportRow row in rows)
29 {
30 if (row is Reading reading)
31 {
32 sum += reading.Celsius;
33 }
34 }
35
36 return sum;
37 }
38
39 // The custom union and Unio variants follow the same shape; Unio uses TryGetT0
40 // instead of the type pattern. The streaming variants skip the array and
41 // consume each row immediately after parsing it.
42}Streaming: a nanosecond per row
| Rows | C# 15 union | Custom [Union] struct | Unio |
|---|---|---|---|
| 10,000 | 27.1 µs, 238 kB | 14.6 µs, 0 B | 16.0 µs, 0 B |
| 1,000,000 | 2.68 ms, 23.8 MB | 1.46 ms, 0 B | 1.64 ms, 0 B |
When each row is consumed immediately, the boxes of the native union never survive a Gen0 collection, yet they still cost time: 2.7 ns per row compared with 1.6 ns for Unio and 1.5 ns for the custom union. In relative terms, that is a large difference. In absolute terms, it is about one nanosecond per row, which is small compared with reading and converting a line of text.
Buffered: the batch size decides
| Rows | Variant | Mean | Allocated | Gen2 collections per 1,000 batches |
|---|---|---|---|---|
| 10,000 | C# 15 union | 37.2 µs | 318 kB | 0 |
Custom [Union] struct | 92.3 µs | 240 kB | 71 | |
| Unio | 110.1 µs | 320 kB | 100 | |
| 1,000,000 | C# 15 union | 25.8 ms | 31.8 MB | 938 |
Custom [Union] struct | 7.1 ms | 24.0 MB | 500 | |
| Unio | 8.2 ms | 32.0 MB | 500 |
With one million rows, avoiding the boxes pays off clearly: the struct-based variants were more than three times faster. The boxes live as long as the batch, survive several collections and are promoted to older generations, so the garbage collector has to trace almost a million objects again and again.
The batch with 10,000 rows shows the opposite result, and it is the more instructive one. Here, the native union was almost three times faster than Unio. The reason is the large object heap. Arrays of 85,000 bytes or more are allocated there, and the large object heap is only collected together with generation 2. The native array of 10,000 references occupies 80,024 bytes and stays just below that threshold. The Unio and custom arrays occupy 320 kB and 240 kB; GC.GetGeneration reports generation 2 for them immediately after allocation, and the benchmark shows the resulting Gen2 collections.
An additional run with 2,000 rows, where every array stays on the small object heap, still favored the native union: 7.1 µs compared with 9.3 µs for the custom union and 9.4 µs for Unio. For small batches, short-lived Gen0 allocations are cheap enough that the wider struct elements do not pay off.
The benchmark allocates a new array per batch on purpose. An importer that reuses its buffers, for example through ArrayPool<T>, avoids the repeated large object heap allocations, which changes the picture for the struct-based variants. In that case, the default-value behavior described earlier becomes even more relevant: stale elements from a previous batch, and for Unio even untouched default elements, look like valid readings.
The results do not produce a universal winner. On this machine, the native union was faster for the batches with 2,000 and 10,000 rows, and the struct-based variants were more than three times faster with one million rows. Where the crossover lies depends on the case types, the batch size and the lifetime of the batch. That is exactly why the measurement belongs in the decision, and why a benchmark that repeatedly matches an already constructed value says little about this importer.
A third option: custom union types
C# 15 does not force the boxing strategy of the generated declaration. Any struct or class marked with [Union] that follows the basic union pattern, a public constructor per case type and a Value property, is treated as a union by the compiler. If the type additionally implements the non-boxing access pattern, a HasValue property and one TryGetValue method per case, the compiler uses those members for type patterns instead of Value:
1[Union]
2public readonly struct ImportRowSlim : IUnion
3{
4 private readonly byte _kind; // 0 = no value, 1 = Reading, 2 = EmptyLine, 3 = InvalidReading
5 private readonly double _celsius;
6 private readonly int _lineNumber;
7 private readonly InvalidReading? _invalid;
8
9 public ImportRowSlim(Reading value) { _kind = 1; _celsius = value.Celsius; }
10 public ImportRowSlim(EmptyLine value) { _kind = 2; _lineNumber = value.LineNumber; }
11 public ImportRowSlim(InvalidReading value) { _kind = 3; _invalid = value; }
12
13 public bool HasValue => _kind != 0;
14
15 public object? Value => _kind switch
16 {
17 1 => new Reading(_celsius),
18 2 => new EmptyLine(_lineNumber),
19 3 => _invalid,
20 _ => null
21 };
22
23 public bool TryGetValue(out Reading value)
24 {
25 value = new Reading(_celsius);
26 return _kind == 1;
27 }
28
29 public bool TryGetValue(out EmptyLine value)
30 {
31 value = new EmptyLine(_lineNumber);
32 return _kind == 2;
33 }
34
35 public bool TryGetValue([NotNullWhen(true)] out InvalidReading? value)
36 {
37 value = _invalid;
38 return _kind == 3;
39 }
40}Consumers use the same switch expressions and is patterns as with a generated union, and the measurements above show the result: no boxes at all and the smallest buffer of the three variants, because the layout is tailored to the actual case types instead of reserving a full slot for each of them.
The price is ownership. The compiler trusts a custom union to follow the documented behavioral rules: Value must only ever return null or one of the case types, the access members must agree with Value, and the default value must be sound. Those rules are not verified by the compiler; they need tests. A custom union is therefore an attractive option for a single, heavily used domain type, and a poor one for dozens of result types across a code base. Unio’s position is exactly the latter case: one tested implementation of typed storage, reused for every arity from 2 to 20.
Narrowing at method boundaries
The strongest functional argument for Unio in this example shows up at a method boundary. Once a valid reading has been added to the sample collection, the diagnostic handler has exactly two possible inputs. TryPickT0 expresses that in its second output parameter:
1using Unio;
2
3public static class ImportBatch
4{
5 public static void Add(
6 Unio<Reading, EmptyLine, InvalidReading> row,
7 ICollection<double> samples,
8 ICollection<string> notices)
9 {
10 if (row.TryPickT0(
11 out Reading reading,
12 out Unio<EmptyLine, InvalidReading> remainder))
13 {
14 samples.Add(reading.Celsius);
15 return;
16 }
17
18 notices.Add(Describe(remainder));
19 }
20
21 private static string Describe(Unio<EmptyLine, InvalidReading> issue) =>
22 issue.Match(
23 static (EmptyLine line) => $"Line {line.LineNumber} is empty.",
24 static (InvalidReading error) =>
25 $"Line {error.LineNumber} contains an invalid temperature '{error.Input}'.");
26}The important line is Describe(remainder). Passing the original row instead does not compile:
1error CS1503: Argument 1: cannot convert from 'Unio.Unio<Reading, EmptyLine, InvalidReading>'
2to 'Unio.Unio<EmptyLine, InvalidReading>'The signature of Describe documents and enforces that it only handles rows that need a diagnostic. Its tests can concentrate on the messages for blank and invalid rows, and no caller can pass a successful reading by mistake. The narrower type exists without a separate declaration.
The native union can express the same contract, but it needs a second named union and an explicit mapping. There is no conversion between unions, even when the case types of one are a subset of the other; passing an ImportRow to a method that expects an ImportIssue fails with the same error CS1503. The mapping happens in the branch that handles each case:
1public union ImportIssue(EmptyLine, InvalidReading);
2
3public static class NativeImportBatch
4{
5 public static void Add(ImportRow row, ICollection<double> samples, ICollection<string> notices)
6 {
7 switch (row)
8 {
9 case Reading reading:
10 samples.Add(reading.Celsius);
11 break;
12 case EmptyLine line:
13 notices.Add(Describe(line));
14 break;
15 case InvalidReading error:
16 notices.Add(Describe(error));
17 break;
18 }
19 }
20
21 public static string Describe(ImportIssue issue) => issue switch
22 {
23 EmptyLine line => $"Line {line.LineNumber} is empty.",
24 InvalidReading error => $"Line {error.LineNumber} contains an invalid temperature '{error.Input}'.",
25 };
26}Each Describe call converts a single case to ImportIssue implicitly. Note that this branching is a switch statement and therefore not checked for completeness; a new case in ImportRow would fall through silently here. Which variant is preferable depends on the vocabulary of the application. If “import issue” is a term used throughout the code base, a named ImportIssue union gives it a contract of its own and is the better design. If the narrower type exists only between two internal methods, TryPick provides it without another declaration.
Equality, hashing and formatting
The generated union does not implement equality. Comparing two ImportRow values falls back to ValueType.Equals, which works but is not designed for performance. The comparison benchmark in the Unio repository
, measured on the same machine as this article, reports 18.49 ns and 80 B allocated per comparison for a built-in union, and 0.94 ns without allocation for Unio’s generated IEquatable<T> implementation. The same benchmark shows the opposite result for matching existing values: a native switch expression over five cases took 0.93 ns, Match with five delegates 1.53 ns.
Formatting follows the same pattern. ToString() on an ImportRow returns only the type name, ImportRow, so log messages that include a union value show nothing about its contents unless the union body overrides ToString. Unio delegates formatting to the active case.
Equality matters as soon as union values are used as dictionary keys, deduplicated in a set or compared in assertions. Where that happens on a hot path, the generated union needs a hand-written Equals and GetHashCode in its body, or a type that provides them.
When the cases share behavior: closed hierarchies
C# 15 introduces a second feature for closed sets of types. The closed modifier restricts derivation from a class to its declaring assembly, so the compiler knows all direct descendants and can check switch expressions for completeness:
1public closed record class ImportResult(int LineNumber);
2public sealed record class ValidRow(int LineNumber, double Celsius) : ImportResult(LineNumber);
3public sealed record class BlankRow(int LineNumber) : ImportResult(LineNumber);
4public sealed record class RejectedRow(int LineNumber, string Input) : ImportResult(LineNumber);A closed hierarchy fits when the cases share data or behavior, here the line number. Every case is a class, so every row is a heap object. For the buffered importer, the object count is therefore comparable to the boxing union: one object per row. Unions fit better when the case types are unrelated, already exist, or are value types. The closed modifier reference describes the rules.
Sharing code between .NET 10 and .NET 11
A nightly import job might still run on .NET 10 while an interactive preview already runs on .NET 11. C# 15 is the default language version for projects that target net11.0, and the union feature relies on UnionAttribute and IUnion, which ship with the .NET 11 runtime. A library that has to serve both applications cannot expose a native union in its public API for the .NET 10 target.
Raising the language version alone does not change that. In a net10.0 project, the default C# 14 does not recognize union as a keyword at all. With <LangVersion>15</LangVersion>, the compiler fails with error CS0518, “Predefined type ‘System.Runtime.CompilerServices.IUnion’ is not defined or imported”, and error CS0656 for the missing UnionAttribute constructor. With hand-written polyfills for both types, the declaration compiled and ran in a test. That configuration, however, is outside what Microsoft supports: “Using a C# language version newer than the version associated with your target TFM isn’t supported”, as the language versioning documentation
states. That is a weak foundation for a library that other teams depend on.
Unio’s runtime packages target .NET 9, 10 and 11. A parser library that multi-targets net10.0 and net11.0 can expose the same Unio<Reading, EmptyLine, InvalidReading> return type to both applications, and both can share the diagnostic formatter and its tests.
That convenience has a longer lifetime than the runtime upgrade. Returning a Unio type makes the library part of the public API. Replacing it later with a native union changes every method signature. Even the order of the generic arguments is part of the contract, because T0 always refers to the first position. Unio’s source generator offers named unions as an alternative, [GenerateUnio] public partial class ImportRowResult : UnioBase<Reading, EmptyLine, InvalidReading>;, but the generated type is a sealed class. Every instance is a heap object, which changes the allocation profile again and belongs in the same performance review.
Decision guide
| Situation | Recommendation |
|---|---|
| .NET 11 only, rows handled immediately | C# 15 union; boxing costs about 1 ns per row |
| Small or medium batches allocated per call | C# 15 union; faster up to 10,000 rows in this measurement |
| Case types are mostly reference types | C# 15 union |
| Cases share data or behavior | Closed hierarchy |
| Large, long-lived buffers of value-type cases | Unio or a custom [Union] struct, confirmed by a measurement |
| One heavily used domain type, native patterns, no dependency | Custom [Union] struct |
| Narrower types between internal methods | Unio with TryPick |
| Narrower types that are part of the domain language | Second named C# 15 union |
| Library shared with .NET 9 or .NET 10 | Unio |
| Equality or hashing on a hot path | Unio, or a union with hand-written equality |
What I would ship
For the streaming .NET 11 importer, I would start with the native ImportRow union, exhaustive switch expressions and an explicit null arm. The boxes it creates die young, the code needs no dependency, and the compiler warns about every new case.
For the buffered variant, the decision belongs to a measurement with real data rather than to a principle. The numbers in this article show that avoiding a million boxes does not reduce memory, because a wider array costs just as much; it reduces the number of objects the garbage collector has to manage. That made the struct-based variants more than three times faster for a million rows and up to three times slower for 10,000. Where large, long-lived batches dominate, a custom [Union] struct is the most compact option for one type, and Unio the more practical one for many.
For the parser shared with the .NET 10 job, I would keep Unio. A runtime upgrade alone is a weak reason to change a public contract that both applications already understand. And even after both applications run on .NET 11, I would keep TryPick where it lets the compiler enforce a useful boundary, such as the signature of Describe, which accepts only the rows that need a diagnostic.
Further reading
Related articles

- 13 min read
Output Caching in ASP.NET Core: What Gets Cached?
ASP.NET Core output caching does not cache an endpoint result, an EF Core query or a domain object. It caches a completed HTTP response: …

- 7 min read
C# 15 Unions: Unions are finally in .NET
After many years of workarounds, design discussions and library-level substitutes, unions are finally becoming a first-class part of C#. The …

- 19 min read
Unio: High-Performance Discriminated Unions for C#
C# is a powerful language, but there is one road it has not yet fully paved: native discriminated union types. Developers have been working …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
