Unions.Pure.Csharp
2.0.11
See the version list below for details.
dotnet add package Unions.Pure.Csharp --version 2.0.11
NuGet\Install-Package Unions.Pure.Csharp -Version 2.0.11
<PackageReference Include="Unions.Pure.Csharp" Version="2.0.11" />
<PackageVersion Include="Unions.Pure.Csharp" Version="2.0.11" />
<PackageReference Include="Unions.Pure.Csharp" />
paket add Unions.Pure.Csharp --version 2.0.11
#r "nuget: Unions.Pure.Csharp, 2.0.11"
#:package Unions.Pure.Csharp@2.0.11
#addin nuget:?package=Unions.Pure.Csharp&version=2.0.11
#tool nuget:?package=Unions.Pure.Csharp&version=2.0.11
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 as properties:
using System.Text.Json.Serialization;
using Unions.Pure.Csharp;
namespace Sample;
[Union(GenerateTarget.Visitor | GenerateTarget.TryOut)]
public partial record struct PaymentStatus
{
[JsonInclude]
[UnionMember]
internal string? Message { get; init; }
[JsonInclude]
[UnionMember]
internal int? Code { get; init; }
}
- Use the generated factories and helpers:
var paid = PaymentStatus.FromCode(200);
var message = paid.Match(
onMessage: s => $"Message: {s}",
onCode: code => $"Code: {code}");
[Union] and [UnionMember] are 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 System.Text.Json.Serialization;
using Unions.Pure.Csharp;
namespace Sample;
[Union(GenerateTarget.All)]
public partial record struct DuplicateTypeUnion
{
[JsonInclude]
[UnionMember("String1")]
internal string? String1 { get; init; }
[JsonInclude]
[UnionMember("String2")]
internal string? String2 { get; init; }
[JsonInclude]
[UnionMember]
internal int? Int32 { get; init; }
}
// 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 + factories)GenerateTarget.IndirectLambdas: delegate-basedMatch/SwitchGenerateTarget.Visitor: visitor-basedMatch<TVisitor, TResult>/Switch<TVisitor>GenerateTarget.TryOut: inlineIsX()/TryGetX(out ...)GenerateTarget.JsonSerialization: enable JSON serialization support (used withSystem.Text.Jsonsource generation)GenerateTarget.All: everything above (default when[Union]is omitted)
JSON serialization (System.Text.Json)
Unions work seamlessly with System.Text.Json source generation. Simply:
- Define your union with properties annotated with
[JsonInclude]and[UnionMember] - Add the union type to your
JsonSerializerContextwith[JsonSerializable(typeof(YourUnion))] - Use
JsonSerializer.SerializeandJsonSerializer.Deserializewith your context
The wire format is a single-property object like {"string2":"hello"} or {"int32":7}.
JSON property names
The JSON property name is derived from the property name or the [UnionMember] name:
- If you used
[UnionMember("CustomName")], the JSON property name is"CustomName"(then the context naming policy is applied when writing). - If you omit the custom name, the property name is used (e.g.
String2→string2with camelCase policy).
Example:
using System.Text.Json;
using System.Text.Json.Serialization;
using Unions.Pure.Csharp;
// Union:
[Union(GenerateTarget.TryOut)]
public partial record struct SomeUnion
{
[JsonInclude]
[UnionMember("String1")]
internal string? String1 { get; init; }
[JsonInclude]
[UnionMember("String2")]
internal string? String2 { get; init; }
[JsonInclude]
[UnionMember]
internal int? Int32 { get; init; }
}
// Context (only need to register the union type, not member types):
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(SomeUnion))]
public partial class ApiJsonContext : JsonSerializerContext;
// Use (AOT friendly, no reflection required):
var ctx = ApiJsonContext.Default;
var u = SomeUnion.FromString2("hello");
var json = JsonSerializer.Serialize(u, ctx.SomeUnion);
var back = JsonSerializer.Deserialize(json, ctx.SomeUnion);
The Tag property is automatically computed from which property is non-null, so it doesn't need to be serialized.
Swagger / OpenAPI (e.g. AOT apps)
Union types live in contract libraries; Swagger wiring belongs in the project that references Swashbuckle.
Contracts (unions only): declare
[Union]types. Do not reference Swashbuckle and do not add[SwaggerUnionSchema]— no Swagger code is emitted there.App / API project (uses Swagger): reference Swashbuckle and declare a partial host class:
using Unions.Pure.Csharp; [SwaggerUnionSchema] public partial class SwaggerUnionGen;In
AddSwaggerGen, call the generated registration on that host:builder.Services.AddSwaggerGen(configure => { SwaggerUnionGen.AddUnionSchemaMappings(configure); configure.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); });
How it works (and why):
- Each assembly that declares
[Union]types emits a small, public, Swashbuckle-free descriptor classUnions.Pure.Csharp.PureUnionsRegistry_<AssemblyName>that exposes each union type and its member names/types. This lives in the contracts library but has no Swagger dependency. - The descriptor is required because union members are declared
internal, and internal members of a referenced assembly are invisible to the Swagger host (the compiler imports only public/protected metadata). The public registry carries the member shapes across the assembly boundary. - The Swagger host project (the one with
[SwaggerUnionSchema]+ Swashbuckle) discovers everyPureUnionsRegistry_*in its whole reference graph and generates a singleISchemaFilterplus the partialSwaggerUnionGen.AddUnionSchemaMappingsentry point.
Each union is mapped to an object schema whose properties are generated through Swashbuckle's own pipeline (so complex member types are registered in components/schemas as proper $refs), and nested types with colliding short names get unique schema ids automatically.
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 |