NoahStolk.UnionStruct
0.5.0
dotnet add package NoahStolk.UnionStruct --version 0.5.0
NuGet\Install-Package NoahStolk.UnionStruct -Version 0.5.0
<PackageReference Include="NoahStolk.UnionStruct" Version="0.5.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="NoahStolk.UnionStruct" Version="0.5.0" />
<PackageReference Include="NoahStolk.UnionStruct"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add NoahStolk.UnionStruct --version 0.5.0
#r "nuget: NoahStolk.UnionStruct, 0.5.0"
#:package NoahStolk.UnionStruct@0.5.0
#addin nuget:?package=NoahStolk.UnionStruct&version=0.5.0
#tool nuget:?package=NoahStolk.UnionStruct&version=0.5.0
union-struct
🚧 WORK IN PROGRESS 🚧
Union-struct is an opinionated zero-dependency source generator that completes C# 15 union types as memory-efficient, allocation-free structs. You declare the case types and the union; the generator writes the storage, the non-boxing pattern-matching support, equality, ToString, and a few helpers.
Requires C# 15 / .NET 11. Version 0.5 is a rewrite on top of the native union feature and is not source compatible with 0.4. For older language versions, stay on 0.4.0; see Migrating from 0.4.
Installation
dotnet add package NoahStolk.UnionStruct
This is an analyzer-only package, so the PackageReference it writes needs no further editing:
<PackageReference Include="NoahStolk.UnionStruct">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
The optional [UnionCase] attribute is generated into your compilation as an internal type in the UnionStruct namespace — there is no assembly to reference, and the package leaves no trace in your build output or in the dependencies of any package you publish. The [Union] attribute is the BCL's own System.Runtime.CompilerServices.UnionAttribute.
Motivation
C# 15 unions give native switch/is and compile-time exhaustiveness, but the compiler synthesizes no bodies. A union that just stores its payload in an object boxes every value-type case. Avoiding that means hand-writing typed storage and a TryGetValue overload per case, plus equality and ToString. This library generates all of that.
It also keeps the reason the library exists: case data lives in public fields, so you can pass a payload by ref and mutate it in place. When every case type is unmanaged (and the union is not generic), the payloads also overlap in memory, like a C union.
This comes at the cost of memory-safety. Writing to a field that is not the active case's can corrupt the active one.
It takes inspiration from:
These are all great libraries. If this library doesn't suit your needs, I recommend checking them out.
Examples
Declaring a union
Declare the case types, then a partial struct with the BCL [Union] attribute and one partial constructor per case. The constructor's parameter type is the case type.
using System.Numerics;
using System.Runtime.CompilerServices; // [Union]
using UnionStruct; // [UnionCase]
public readonly record struct Circle<T>(T Radius);
public readonly record struct Rectangle<T>(T Width, T Height);
[Union]
public partial struct Shape<T> where T : INumber<T>
{
public partial Shape(Circle<T> value);
[UnionCase(DisplayName = "Rect")]
public partial Shape(Rectangle<T> value);
}
Case types must be distinct. A case without data is an empty struct, so enum-like unions nest them:
[Union]
public readonly partial struct Medal
{
public readonly record struct Bronze;
public readonly record struct Silver;
public readonly record struct Gold;
public partial Medal(Bronze _);
public partial Medal(Silver _);
public partial Medal(Gold _);
}
Constructing and matching
Shape<float> shape = new Circle<float>(2f); // implicit conversion, or new Shape<float>(new Circle<float>(2f))
float area = shape switch
{
Circle<float> c => c.Radius * c.Radius,
Rectangle<float> r => r.Width * r.Height,
}; // exhaustive: no default arm, no allocation
Adding a case later turns every switch expression that misses it into warning CS8509. Add <WarningsAsErrors>$(WarningsAsErrors);CS8509</WarningsAsErrors> to your project to enforce it.
ref access to the payload
Each case's payload is a public field named <Case>Data, where <Case> is the case type's name without type arguments:
ref Circle<float> slot = ref shape.CircleData;
slot = slot with { Radius = 9f };
What is generated
For each union, the generator emits:
CaseCount, a<Case>Indexconstant per case, and apublic readonly int CaseIndexfield;- a public
<Case>Datafield per case, overlapped with[FieldOffset]when every case type is unmanaged and the union is not generic; - the implementing half of each partial constructor, and an implicit conversion from each case type;
Value(theIUnioncontract; it boxes, so pattern matching never uses it) and a non-boxingTryGetValue(out TCase)per case;IEquatable<T>,Equals,GetHashCode,==and!=;ToString, formatted as<Name> { Value = <payload> }, or just<Name>when the case type is a struct without fields (it has only one value);GetTypeString,GetTypeAsUtf8Span(static by case index, or for the current case) andNullTerminatedMemberNames, which use the case's name or itsDisplayName.
Case names
A case is named after its type, without type arguments: Circle<T> gives CircleIndex and CircleData, int? gives NullableInt32… and int[] gives Int32Array…. [UnionCase(Name = "…")] overrides it. You need that when two case types share a name (Foo.Circle and Bar.Circle, or Circle<int> and Circle<float>), which is otherwise an error, and for tuple case types, which have no name of their own:
[Union]
public partial struct Radius
{
[UnionCase(Name = "IntCircle")]
public partial Radius(Circle<int> value); // IntCircleIndex, IntCircleData
[UnionCase(Name = "FloatCircle", DisplayName = "Circle (float)")]
public partial Radius(Circle<float> value); // FloatCircleIndex, FloatCircleData
}
Name must be a valid identifier, because it is the stem of the generated members. DisplayName only changes strings and defaults to the name. Matching never uses either: cases are matched by type, as in case Circle<int> c.
Migrating from 0.4
- Declare a case type for each case. Use a record struct for a multi-parameter case and an empty struct for a case without data.
- Replace
[UnionStruct.Union]with[System.Runtime.CompilerServices.Union]. - Replace each
[UnionCase] public static partial U Foo(T value);withpublic partial U(FooType value);. KeepDisplayNameif you had one, and addName = "Foo"when the case type isn't namedFoo. - Construction:
U.Foo(x)becomesnew U(new FooType(x)), or relies on the implicit conversion. - Matching:
Switch,Match,Is<Case>,TagandCaseTagare gone. Useu switch { FooType f => … }andu is FooType. ref u.FooDatakeeps working as long as the case is namedFoo, either through its type name orName.- Add
<WarningsAsErrors>$(WarningsAsErrors);CS8509</WarningsAsErrors>. It replaces theUS0001analyzer.
Benchmarks
TODO
Development
Debugging the Source Generator
To debug the source generator, use the launchSettings.json file in the UnionStruct project to run the generator against the UnionStruct.Sample project.
You can also debug the generator tests using the UnionStruct.Tests project.
Snapshot Testing
To simply accept all snapshots immediately, run
./scripts/accept-all.sh src/UnionStruct.Tests/snapshotsfrom the root of the repository.
To control which diff tool is used for snapshot testing, use the DiffEngine_ToolOrder environment variable.
In JetBrains Rider, this can be configured under Build, Execution, Deployment > Unit Testing > Test Runner > Environment variables.
You can also disable DiffEngine by setting the DiffEngine_Disable environment variable to true.
Learn more about Target Frameworks and .NET Standard.
This package has no dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.5.0 | 52 | 11/20/2026 |
| 0.4.0 | 591 | 8/8/2026 |
| 0.3.0 | 520 | 5/14/2026 |
| 0.2.2 | 757 | 3/3/2026 |
| 0.2.1 | 3,991 | 7/19/2025 |
| 0.2.0 | 889 | 6/11/2025 |
| 0.1.0 | 1,496 | 3/16/2025 |
| 0.0.0-alpha.6 | 237 | 2/13/2025 |
| 0.0.0-alpha.5 | 187 | 12/19/2024 |
| 0.0.0-alpha.4 | 160 | 12/18/2024 |
| 0.0.0-alpha.3 | 154 | 12/18/2024 |
| 0.0.0-alpha.2 | 159 | 12/4/2024 |
| 0.0.0-alpha.1 | 137 | 12/2/2024 |
| 0.0.0-alpha.0 | 144 | 12/2/2024 |