Your own unions¶
This page covers declaring a union, the Is and As helpers that work on any union, and UnionJsonConverter, which writes the case name so the union can be read back from JSON.
Declaring a union¶
A union lists its case types. Each case converts to the union implicitly, and switch checks that every case is handled:
public record Card(string Last4);
public record BankTransfer(string Iban);
public record Voucher(string Code);
public union PaymentMethod(Card, BankTransfer, Voucher);
PaymentMethod method = new Card("4242");
string description = method switch
{
Card card => $"Card ending {card.Last4}",
BankTransfer bank => $"Transfer from {bank.Iban}",
Voucher voucher => $"Voucher {voucher.Code}"
};
// "Card ending 4242"
The held case is available as method.Value, typed object?. It is null only for a default union. A union is a struct, and default holds nothing: a switch over it throws SwitchExpressionException unless an arm matches null. The compiler does not warn about a missing null arm.
Cases may be any type, not only records. Use records when each case carries data, because their ToString and equality are useful in logs and tests.
Is and As¶
Both helpers live in Fluent.Unions and work on every union, including Result<T> and Option<T>, because every union implements .NET's IUnion.
| Helper | Returns |
|---|---|
Is<TCase>() |
true when the union holds a TCase. |
As<TCase>() |
An Option<TCase> with the case, or None when the union holds anything else, or nothing. |
using Fluent.Unions;
bool isCard = method.Is<Card>(); // true
Option<BankTransfer> transfer = method.As<BankTransfer>(); // None
As returns an option, so it chains with the option operators:
string last4 = method.As<Card>().Select(card => card.Last4).GetValueOrDefault("none"); // "4242"
Prefer switch when you handle several cases. Use Is and As when you care about one.
A union value type is boxed when it is passed to either helper, because the parameter is an IUnion. This is one small allocation per call. It does not matter in a request handler, but think twice in a tight loop.
JSON with UnionJsonConverter¶
By default, System.Text.Json writes only the value of a union. That cannot be read back when cases look alike, and it does not say which case it was. Apply UnionJsonConverter to write the case name as well:
using System.Text.Json;
using System.Text.Json.Serialization;
using Fluent.Unions.Serialization;
[JsonConverter(typeof(UnionJsonConverter))]
public union PaymentMethod(Card, BankTransfer, Voucher);
public record Checkout(Guid Id, PaymentMethod Method);
var json = JsonSerializer.Serialize(new Checkout(Guid.Empty, new Card("4242")));
{"Id":"00000000-0000-0000-0000-000000000000","Method":{"$type":"Card","$value":{"Last4":"4242"}}}
Reading is the reverse:
var method = JsonSerializer.Deserialize<PaymentMethod>("""{ "$value": { "Code": "SAVE5" }, "$type": "Voucher" }""");
// Voucher { Code = SAVE5 }
Reading and writing rules¶
- Order does not matter when reading.
$typeand$valuemay come in either order, as in the example above. The converter always writes$typefirst. - An empty union is
null. Adefaultunion writesnull, andnullreads as adefaultunion. - Case names come from the type name. By default,
$typeis the name of the case type without its namespace, so anintcase is"Int32".[UnionCaseName]sets another name. - Unknown or missing
$typethrowsJsonException.{"$type":"Cash","$value":{}}fails with'Cash' is not a case of PaymentMethod.. A missing$type, or{"$type":null}, fails withA PaymentMethod needs a '$type' property.. - A missing
$valuethrowsJsonException, and so does a$valuethat would give an empty union. - Case names must be unique. Two cases with the same type name, from different namespaces or closed generics such as
List<int>andList<string>, cannot be told apart. The first serialization throws anInvalidOperationException("has several cases named 'Card'") that names both types. Give the cases distinct names with[UnionCaseName], see Stable case names. - Renaming a case type renames it in JSON. Pin the stored name with
[UnionCaseName(typeof(NewType), "OldName")]before the rename.
In a trimmed or native AOT app, apply UnionJsonConverter<PaymentMethod> instead of the factory. See AOT and trimming.
Pattern matching tips¶
- Match on the case type directly. Write
Card card => ..., not a test onmethod.Value. - Do not add a discard arm.
_ => ...silences CS8509, so adding a case later no longer warns you. Name every case. - Combine cases that behave alike with
Card or Voucher => .... - Match on a pair for transitions.
(state, command) switch { (Draft draft, Submit) => ... }handles each valid combination. See Modeling with unions. - Use
whenfor rules inside a case.Card { Last4: "0000" } => ...orCard c when c.Last4 == "0000" => ...does not hide the other cases from the exhaustiveness check. - Make CS8509 an error with
<WarningsAsErrors>CS8509</WarningsAsErrors>, so a missing case breaks the build.
Pitfalls¶
- A
defaultunion reaches aswitchwithout a matching arm and throws. Initialize fields and properties of union type. - Without
[JsonConverter(typeof(UnionJsonConverter))], the case name is not written. IsandAscheck the held value's type. A subclass ofTCasecounts as aTCase.- Do not add a
HasValueproperty with another meaning. The compiler uses a union'sHasValuefor thenullpattern. AHasValuethat isfalsefor some cases makesnullmatch those cases too. Name such a property after its meaning, asLoadable<T>.IsLoadeddoes.
See also¶
- Loadable: a library union for asynchronous UI state.
- Modeling with unions: state machines and event sourcing.
test/Fluent.Unions.Tests/UnionHelperTests.csin the repo: the behavior above as tests.