Skip to content

Discriminated Unions

github-actions[bot] edited this page Nov 30, 2026 · 4 revisions

Discriminated Unions (Ferrous.Unions)

Ferrous.Unions is an incremental Roslyn source generator (IIncrementalGenerator) that turns a [DiscriminatedUnion] readonly partial struct (or recursive abstract partial record) into a zero-boxing tagged union—with automatic .NET 11 / C# 15 [Union] light-up.


Example: Modeling Payment Webhook Events

In vanilla .NET, modeling a closed set of event variants usually means either a "fat DTO" with nullable properties (making illegal states representable) or an abstract record hierarchy (allocating on the heap for every event and requiring a _ => throw ... fallback in switch expressions):

// Vanilla C#: illegal combinations of fields compile cleanly
public sealed class PaymentEvent
{
    public string Kind { get; init; } = "";
    public decimal? Amount { get; init; }       // Only valid for Charged / Refunded
    public string? FailureReason { get; init; } // Only valid for Failed
    public string? DisputeId { get; init; }     // Only valid for Disputed
}

With Ferrous.Unions, each variant carries only its valid payload inside a zero-boxing readonly struct, with compiler-enforced exhaustive Match(...) (and native C# 15 exhaustive switch on .NET 11+):

using Ferrous;

[DiscriminatedUnion]
public readonly partial struct PaymentEvent
{
    public static partial PaymentEvent Charged(decimal amount, string currency);
    public static partial PaymentEvent Refunded(decimal amount);
    public static partial PaymentEvent Failed(string reason);
    public static partial PaymentEvent Disputed(string disputeId);
}

// Works on .NET 10 and .NET 11 with zero heap allocation and zero boxing:
string summary = evt.Match(
    onCharged: (amount, currency) => $"Charged {amount} {currency}",
    onRefunded: amount => $"Refunded {amount}",
    onFailed: reason => $"Failed: {reason}",
    onDisputed: id => $"Dispute opened: {id}");

// On .NET 11 / C# 15, [Union] lights up automatically for native exhaustive switch:
string summaryNet11 = evt switch
{
    PaymentEvent.ChargedCase c => $"Charged {c.amount} {c.currency}",
    PaymentEvent.RefundedCase r => $"Refunded {r.amount}",
    PaymentEvent.FailedCase f => $"Failed: {f.reason}",
    PaymentEvent.DisputedCase d => $"Dispute opened: {d.disputeId}",
};

If you later add public static partial PaymentEvent Voided();, every Match(...) call site fails to compile until the new case is handled.

Recursive Unions (ASTs / Expressions)

For recursive data structures that cannot be value types, apply [DiscriminatedUnion] to an abstract partial record:

[DiscriminatedUnion]
public abstract partial record Expr
{
    public sealed partial record Literal(int Value) : Expr;
    public sealed partial record Add(Expr Left, Expr Right) : Expr;
    public sealed partial record Negate(Expr Inner) : Expr;
}

thiserror-Style Error Unions ([ErrorMessage], Implicit From, & NativeAOT JSON)

[DiscriminatedUnion(GenerateJsonConverter = true)]
public readonly partial struct ApiError
{
    [ErrorMessage("Resource '{id}' was not found.")]
    public static partial ApiError NotFound(int id);

    [ErrorMessage("Upstream timeout: {reason}")]
    public static partial ApiError Timeout(string reason);
}

// Implicit conversion for unique single-parameter payload variants + FormatError()
ApiError err = 404; // -> ApiError.NotFound(404)
string msg = err.FormatError(); // "Resource '404' was not found."

Strongly Typed [Newtype] Wrappers (FE0101)

Generate zero-overhead readonly partial struct wrappers implementing IEquatable<T>, IComparable<T>, IParsable<T>, ISpanFormattable, [NoDefault], NativeAOT-safe JSON converters, and optional smart-constructor TryCreate(...) validation:

[Newtype(typeof(string))]
public readonly partial struct Email
{
    private static bool TryValidate(string value, out string error)
    {
        if (string.IsNullOrWhiteSpace(value) || !value.Contains('@'))
        {
            error = "Invalid email address.";
            return false;
        }

        error = string.Empty;
        return true;
    }
}

Result<Email, string> parsed = Email.TryCreate("ada@example.com");

#[tracing::instrument]-Style Span Generation ([Instrument])

Ferrous.Unions also includes InstrumentGenerator for [Instrument] partial methods, emitting zero-reflection System.Diagnostics.ActivitySource spans with automatic parameter tagging:

public sealed partial class OrderService
{
    [Instrument("orders.load", SourceName = "Acme.Orders")]
    public partial Order Load(int orderId, string region);

    private Order LoadCore(int orderId, string region) => /* ... */;
}

Benefits Over Vanilla .NET

Concern Vanilla .NET (Fat DTO / abstract record) [DiscriminatedUnion]
Illegal states Nullable fields allow mixed/missing payloads Impossible—each variant only carries its own fields
Duplicate payload types OneOf<int, int> collides Width(int) and Height(int) work cleanly by name
Heap allocations Reference-type records allocate per event readonly struct unions allocate 0 bytes
Exhaustiveness _ => throw ... rots silently Compile-time error when a new variant is added
Uninitialized default Silently valid Caught at compile time by FE0404
Inspect generated code N/A dotnet fe expand prints the exact generated .g.cs

Clone this wiki locally