Unions.Pure.Csharp
1.0.10
See the version list below for details.
dotnet add package Unions.Pure.Csharp --version 1.0.10
NuGet\Install-Package Unions.Pure.Csharp -Version 1.0.10
<PackageReference Include="Unions.Pure.Csharp" Version="1.0.10" />
<PackageVersion Include="Unions.Pure.Csharp" Version="1.0.10" />
<PackageReference Include="Unions.Pure.Csharp" />
paket add Unions.Pure.Csharp --version 1.0.10
#r "nuget: Unions.Pure.Csharp, 1.0.10"
#:package Unions.Pure.Csharp@1.0.10
#addin nuget:?package=Unions.Pure.Csharp&version=1.0.10
#tool nuget:?package=Unions.Pure.Csharp&version=1.0.10
C# Pure Unions
Roslyn source generator for minimal-overhead discriminated unions. Add [UnionMember] attributes to a partial type and the generator emits a compact tag enum, factory helpers, and Match/Switch helpers without extra allocations.
Getting started
- Install the package in your project:
dotnet add package Unions.Pure.Csharp
- Annotate a partial type with the union members you need:
using Unions.Pure.Csharp;
namespace Sample;
[UnionMember(typeof(string))]
[UnionMember(typeof(int))]
[UnionGenerator(GenerateTarget.Visitor | GenerateTarget.TryOut)]
public partial record struct PaymentStatus;
- Use the generated factories and helpers:
var paid = PaymentStatus.FromInt32(200);
var message = paid.Match(
onString: s => $"Message: {s}",
onInt32: code => $"Code: {code}");
[UnionMember] is injected by the generator; no manual reference is required beyond the package itself.
API choices (performance vs ergonomics)
Generated unions expose three ways to consume values:
GenerateTarget.IndirectLambdas: delegate-basedMatch/Switch(Func<>/Action<>)- Pros: nicest call site; familiar functional style.
- Cons: still does delegate
Invoke(typically an indirect call); capturing lambdas allocate (closures/delegates).
GenerateTarget.Visitor: visitor-basedMatch<TVisitor, TResult>/Switch<TVisitor>(genericstructvisitors)- Pros: avoids delegate
Invoke; JIT can inline; no allocations. - Cons: requires a small
structvisitor type (can be local/private).
- Pros: avoids delegate
GenerateTarget.TryOut: inlineIsX()/TryGetX(out ...)- Pros: “plain C#”
if/else; no delegates; no visitors; no indirect calls. - Cons: more boilerplate at call site vs
Match.
- Pros: “plain C#”
Note on OneOf (comparison)
OneOf is a solid library, but for hot paths it has the same core drawback as any delegate-based API: Match/Switch ultimately invoke delegates (indirect calls), and capturing lambdas allocate. It also needs to handle invalid state (cold path that throws).
Duplicate member types example
If you use the same type multiple times, provide distinct names:
using Unions.Pure.Csharp;
namespace Sample;
[UnionMember(typeof(string), "String1")]
[UnionMember(typeof(string), "String2")]
[UnionMember(typeof(int))]
[UnionGenerator(GenerateTarget.All)]
public partial record struct DuplicateTypeUnion;
// Usage:
var u = DuplicateTypeUnion.FromString2("hello");
var lenOrInt = u.Match(
onString1: s => s.Length,
onString2: s => s.Length,
onInt32: i => i);
GenerateTarget flags
GenerateTarget.None: generate nothing extra (still generates tag + fields + factories)GenerateTarget.IndirectLambdas: delegate-basedMatch/SwitchGenerateTarget.Visitor: visitor-basedMatch<TVisitor, TResult>/Switch<TVisitor>GenerateTarget.TryOut: inlineIsX()/TryGetX(out ...)GenerateTarget.All: everything above (default when[UnionGenerator]is omitted)
JSON serialization (System.Text.Json)
The generator can emit AOT-friendly JSON helpers when you specify a source-generated JsonSerializerContext:
- Add
[UnionSerializationContext(typeof(YourJsonSerializerContext))]on the union - The generator will emit
ToUtf8Bytes()andFromUtf8Bytes(...) - The wire format is a single-property object like
{"string2":"hello"}or{"int32":7}
Disclaimer (why the JsonSerializerContext lives outside generated code)
This JSON support is a pragmatic workaround for the fact that you can’t reliably “chain” source generators: this generator can emit union code, but it can’t also ensure that System.Text.Json’s source generator sees and processes new types/attributes emitted by another generator in the same compilation in a dependable way.
Because of that, the JsonSerializerContext (and its [JsonSerializable(...)] roots) must be written in your project (non-generated code) so the STJ source generator runs over it normally. The union generator then consumes that context at runtime via the JsonTypeInfo APIs.
JSON field name mirrors [UnionMember] name
The JSON property name is derived from the union member’s tag name:
- If you used
[UnionMember(typeof(T), "CustomName")], the JSON property name is"CustomName"(then the context naming policy is applied when writing). - If you omit the custom name, the generator uses its inferred tag identifier (e.g.
string→String,int→Int32, arrays →Int32Array), and that is what gets mirrored to JSON (again, with naming policy applied when writing).
When reading, FromUtf8Bytes matches the single property name case-sensitively by default, and it accepts both:
- The raw tag name (e.g.
Payload) - The tag name after applying the context’s
PropertyNamingPolicy(e.g.payloadfor camelCase)
If you want case-insensitive behavior, enable it:
[UnionSerializationContext(typeof(ApiJsonContext), caseInsensitivePropertyNameMatching: true)]
Example:
using System.Text.Json;
using System.Text.Json.Serialization;
using Unions.Pure.Csharp;
// Union:
[UnionMember(typeof(string), "String1")]
[UnionMember(typeof(string), "String2")]
[UnionMember(typeof(int))]
[UnionGenerator(GenerateTarget.TryOut)]
[UnionSerializationContext(typeof(ApiJsonContext))]
public partial record struct SomeUnion;
// Context (add all payload/root types you plan to serialize):
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof(int))]
public partial class ApiJsonContext : JsonSerializerContext;
// Use (AOT friendly, no reflection required):
var bytes = SomeUnion.FromString2("hello").ToUtf8Bytes();
var back = SomeUnion.FromUtf8Bytes(bytes);
[UnionSerializationContext] is injected by the generator, just like [UnionMember].
Learn more about Target Frameworks and .NET Standard.
-
.NETStandard 2.0
- 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 |
|---|---|---|
| 2.0.12 | 5,234 | 6/18/2026 |
| 2.0.11 | 168 | 6/18/2026 |
| 2.0.10 | 318 | 5/15/2026 |
| 2.0.9 | 124 | 5/15/2026 |
| 2.0.8 | 127 | 5/15/2026 |
| 2.0.7 | 126 | 5/15/2026 |
| 2.0.6 | 139 | 5/15/2026 |
| 2.0.5 | 149 | 2/18/2026 |
| 2.0.4 | 133 | 2/18/2026 |
| 2.0.3 | 2,628 | 1/15/2026 |
| 2.0.2 | 338 | 12/18/2025 |
| 2.0.1 | 315 | 12/18/2025 |
| 2.0.0 | 752 | 12/15/2025 |
| 1.1.0 | 296 | 12/15/2025 |
| 1.0.10 | 271 | 12/15/2025 |
| 1.0.8 | 259 | 12/14/2025 |
| 1.0.7 | 252 | 12/14/2025 |
| 1.0.6 | 261 | 12/14/2025 |
| 1.0.5 | 259 | 12/14/2025 |
| 1.0.4 | 256 | 12/14/2025 |