Lumine.DiscriminatedUnion
1.0.2
dotnet add package Lumine.DiscriminatedUnion --version 1.0.2
NuGet\Install-Package Lumine.DiscriminatedUnion -Version 1.0.2
<PackageReference Include="Lumine.DiscriminatedUnion" Version="1.0.2" />
<PackageVersion Include="Lumine.DiscriminatedUnion" Version="1.0.2" />
<PackageReference Include="Lumine.DiscriminatedUnion" />
paket add Lumine.DiscriminatedUnion --version 1.0.2
#r "nuget: Lumine.DiscriminatedUnion, 1.0.2"
#:package Lumine.DiscriminatedUnion@1.0.2
#addin nuget:?package=Lumine.DiscriminatedUnion&version=1.0.2
#tool nuget:?package=Lumine.DiscriminatedUnion&version=1.0.2
DiscriminatedUnion
DiscriminatedUnion — This is a Source Generator for C# that generates discriminated union / tagged union on top of partial struct and partial class.
The library allows you to describe a union through attributes, and then automatically obtain:
TagIsXxx-properties- properties of cases
- factory methods
FromXxx(...) Match(...)Switch(...)TryGetXxx(...)implicit operatorEquals,GetHashCode,ToString
The main idea of implementation:
- Unmanaged value types are stored in a single overlapped storage using
StructLayout(LayoutKind.Explicit) - Reference types are stored in a single
objectfield - Managed structs (structures with reference fields inside) are also stored using
object - Readonly structs are supported
- Unit cases without data are supported
Possibilities
- Generating DUs from attributes
- Named cases
- Support for identical CLR types in different cases:
Width: intHeight: int- Support for
readonly partial structandpartial class - Unit-case support:
LoadingNoneCancelled- Zero-allocation for unmanaged value types
- Fully type-safe API
Installation
If the package is published to NuGet:
dotnet add package DiscriminatedUnion
Quick start
using DiscriminatedUnion;
[UnionCase("Number", typeof(int))]
[UnionCase("Text", typeof(string))]
[UnionCase("Flag", typeof(bool))]
public partial struct Value {
}
After generation you can write:
Value a = 42;
Value b = "hello";
Value c = true;
Console.WriteLine(a.Tag); // Number
Console.WriteLine(a.IsNumber); // true
Console.WriteLine(a.Number); // 42
var result = b.Match(
onNumber: n => $"int: {n}",
onText: t => $"text: {t}",
onFlag: f => $"flag: {f}"
);
Console.WriteLine(result); // text: hello
Example: Result
using DiscriminatedUnion;
[UnionCase("Ok", typeof(int))]
[UnionCase("Error", typeof(string))]
[UnionCaseUnit("Loading")]
public readonly partial struct Result {
}
Usage:
var ok = Result.FromOk(200);
var err = Result.FromError("Not found");
var loading = Result.FromLoading();
Console.WriteLine(ok.Tag); // Ok
Console.WriteLine(ok.IsOk); // true
Console.WriteLine(ok.Ok); // 200
var text = err.Match(
onOk: code => $"OK: {code}",
onError: message => $"ERROR: {message}",
onLoading: () => "LOADING"
);
Console.WriteLine(text);
Since the structure is readonly, all case properties will be read-only.
Example: mutable union
using DiscriminatedUnion;
[UnionCase("Int32", typeof(int))]
[UnionCase("String", typeof(string))]
[UnionCase("Boolean", typeof(bool))]
public partial struct PrimitiveValue {
}
Usage:
var value = PrimitiveValue.FromInt32(10);
Console.WriteLine(value.Int32); // 10
value.Boolean = true;
Console.WriteLine(value.Tag); // Boolean
Console.WriteLine(value.IsBoolean); // true
Console.WriteLine(value.Boolean); // true
Example: read-only case
using DiscriminatedUnion;
[UnionCase("Id", typeof(int))]
[UnionCase("Name", typeof(string), ReadOnly = true)]
public partial struct PersonField {
}
Usage:
var a = PersonField.FromName("Alice");
Console.WriteLine(a.Name);
// a.Name = "Bob"; // setter не будет сгенерирован
var b = PersonField.FromId(10);
b.Id = 20; // допустимо
Example: same types in different cases
using DiscriminatedUnion;
[UnionCase("Width", typeof(int))]
[UnionCase("Height", typeof(int))]
public partial struct Dimension {
}
Usage:
var w = Dimension.FromWidth(100);
var h = Dimension.FromHeight(200);
Console.WriteLine(w.IsWidth); // true
Console.WriteLine(w.Width); // 100
Console.WriteLine(h.IsHeight); // true
Console.WriteLine(h.Height); // 200
Example: unit-case
using DiscriminatedUnion;
[UnionCaseUnit("None")]
[UnionCase("Value", typeof(string))]
public partial struct OptionalText {
}
Usage:
var a = OptionalText.FromNone();
var b = OptionalText.FromValue("hello");
Console.WriteLine(a.IsNone); // true
Console.WriteLine(b.IsValue); // true
var text = b.Match(
onNone: () => "<empty>",
onValue: s => s
);
What is generated
For each union the following are generated:
1. Enum tag
public enum UnionTag : byte {
None = 0,
Ok = 1,
Error = 2,
Loading = 3
}
2. Property Tag
public UnionTag Tag { get; }
3. Case studies
public bool IsOk { get; }
public bool IsError { get; }
public bool IsLoading { get; }
4. Properties of cases
public int Ok { get; }
public string Error { get; }
or, if the union is not readonly and the case is not marked ReadOnly = true:
public int Ok { get; set; }
5. Factory methods
public static Result FromOk(int value)
public static Result FromError(string value)
public static Result FromLoading()
6. Pattern matching
public TResult Match<TResult>(...)
public void Switch(...)
7. TryGet API
public bool TryGetOk(out int value)
public bool TryGetError(out string value)
public bool TryGetLoading()
8. Additionally
public static implicit operator Result(int value)
public static implicit operator Result(string value)
public bool Equals(Result other)
public override bool Equals(object? obj)
public override int GetHashCode()
public override string ToString()
Terms of Use
Union must be a partial struct
[UnionCase("Ok", typeof(int))]
[UnionCase("Error", typeof(string))]
public partial struct Result {
}
For readonly union
[UnionCase("Ok", typeof(int))]
[UnionCase("Error", typeof(string))]
public readonly partial struct Result {
}
Attributes
Cases with data
[UnionCase("Ok", typeof(int))]
[UnionCase("Error", typeof(string))]
Read-only case
[UnionCase("Name", typeof(string), ReadOnly = true)]
Unit-case
[UnionCaseUnit("Loading")]
Storage model
The generator uses the following scheme:
Tag— active case_refValue: object?— for reference types and managed structs_valValue— explicit-layout union for unmanaged value types
This allows:
- avoiding boxing of
int,bool,double,Guid, and other unmanaged types - safe storage of reference types for the GC
- avoiding mixing reference fields and raw overlaps in the same memory
What types are stored where?
In _valValue
intbooldoubleGuid- other
unmanaged struct
In _refValue
stringobjectException- any class
- value types that are not unmanaged
Example of managed struct:
public struct UserInfo {
public int Id;
public string Name;
}
This type will be stored via object because there is a string reference inside.
Restrictions
1. Using structures and classes
Support for class begins with version 1.0.2
2. Case name must be a valid C# identifier.
For example:
[UnionCase("Ok", typeof(int))]
But you shouldn't use names like these:
[UnionCase("not-valid-name", typeof(int))]
3. If two cases have the same CLR type, no implicit conversion is generated.
For example:
[UnionCase("Width", typeof(int))]
[UnionCase("Height", typeof(int))]
public partial struct Dimension
{
}
It is not possible to generate safely here:
public static implicit operator Dimension(int value)
Because it's unclear which case to cast int to.
In this case, you need to use factory methods:
var x = Dimension.FromWidth(100);
4. Unit-case does not have a value property
Generated for him:
IsXxxFromXxx()TryGetXxx()- branches in
Match/Switch
5 UnionImmutableAttribute (v1.0.2)
The UnionImmutable attribute makes the type readonly, the type and values cannot be changed
Project status
The project generates code for DU at compile time and focuses on:
- expressible domain model
- allocation minimization
- convenient API for pattern matching
- support for
readonly struct
If you are using the library in production, we recommend:
- enabling tests for generated union types
- checking generated output in CI
- committing the package version
License
This project is distributed under license GNU General Public License v3.0.
License text:
In short: If you distribute a derivative work or binary distribution covered by the GPLv3, you must comply with the terms of that license.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
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.