{"id":13629567,"url":"https://github.com/mknejp/dotvariant","last_synced_at":"2026-02-20T23:47:25.183Z","repository":{"id":42452562,"uuid":"356356473","full_name":"mknejp/dotvariant","owner":"mknejp","description":"A type-safe and space-efficient sum type for C# (comparable to discriminated unions in C or C++)","archived":false,"fork":false,"pushed_at":"2024-09-03T21:21:39.000Z","size":603,"stargazers_count":73,"open_issues_count":16,"forks_count":3,"subscribers_count":6,"default_branch":"stable","last_synced_at":"2025-10-06T12:48:02.337Z","etag":null,"topics":["algebraic-data-types","csharp","csharp-sourcegenerator","discriminated-unions","functional","sum-types","union","variant"],"latest_commit_sha":null,"homepage":"https://twitter.com/mknejp","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mknejp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSES/BSL-1.0.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS.txt","dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-04-09T17:54:52.000Z","updated_at":"2025-05-30T18:31:32.000Z","dependencies_parsed_at":"2025-04-17T10:31:21.016Z","dependency_job_id":"77905950-0158-495c-98c4-e6207a27f5c4","html_url":"https://github.com/mknejp/dotvariant","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"purl":"pkg:github/mknejp/dotvariant","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mknejp%2Fdotvariant","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mknejp%2Fdotvariant/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mknejp%2Fdotvariant/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mknejp%2Fdotvariant/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mknejp","download_url":"https://codeload.github.com/mknejp/dotvariant/tar.gz/refs/heads/stable","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mknejp%2Fdotvariant/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29668055,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-20T23:24:07.480Z","status":"ssl_error","status_checked_at":"2026-02-20T23:24:06.202Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algebraic-data-types","csharp","csharp-sourcegenerator","discriminated-unions","functional","sum-types","union","variant"],"created_at":"2024-08-01T22:01:13.766Z","updated_at":"2026-02-20T23:47:20.175Z","avatar_url":"https://github.com/mknejp.png","language":"C#","readme":"\u003c!--\nSPDX-FileCopyrightText: 2021 The dotVariant Authors (see AUTHORS.txt)\n\nSPDX-License-Identifier: BSL-1.0\n--\u003e\n\n# dotVariant [![GitHub](https://img.shields.io/github/license/mknejp/dotVariant)](/LICENSE.txt) [![Nuget verion](https://img.shields.io/nuget/v/dotVariant)](https://www.nuget.org/packages/dotVariant/) [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/mknejp/dotvariant/test-package)](https://github.com/mknejp/dotvariant/actions)\n\nA type-safe and space-efficient sum type for C# (comparable to unions in C or C++)\n\n- [Overview of Variants](#overview-of-variants)\n  - [Declaring a Variant](#declaring-a-variant)\n  - [Using a Variant](#using-a-variant)\n  - [Custom Value Types](#custom-value-types)\n  - [Nullability](#nullability)\n  - [Emptiness](#emptiness)\n- [Generated Code Features](#generated-code-features)\n  - [`IDisposable` Support](#idisposable-support)\n  - [External Integrations: `IEnumerable\u003cT\u003e`, `IObservable\u003cT\u003e`](#external-integrations)\n- [Customization](#customization)\n  - [Extension Class Namespace](#extension-class-namespace)\n- [Compatibility](#compatibility)\n- [License](#license)\n\n## Overview of Variants\n\nA variant is similar to a struct or class, except that it can always only contain _one_ of its fields. A `class` declared with an `int` and a `string` property always contains one `int` value and one `string` value. In comparison to that a variant declared with an `int` option and a `string` option always contains _either_ an `int` value _or_ a `string` value, but never both. The library also makes a best effort at minimizing the amount of storage required by the variant as it can always only contain a single value. This is similar to C and C++ `union`, but tweaked to work under the restrictions of the .NET runtime.\n\n### Declaring a Variant\n\nDeclaring a variant is very easy and requires only minimal amount of\n\n```csharp\nusing dotVariant;\n\nnamespace MyNamespace\n{\n  [Variant] // required attribute\n  partial class MyVariant // \"partial\" is mandatory\n  {\n      // \"static partial\" is mandatory. Do not implement!\n      static partial void VariantOf(int a, double d, string s);\n  }\n  [Variant]\n  partial class MyVariant\u003cA, B, C\u003e // Variants can have type parameters\n  {\n      static partial void VariantOf(A a, B b, C c);\n  }\n}\n```\n\nYou are not restricted to just `class`. You can also use `struct`, `readonly struct`, `ref struct`, and so on. Only `record` is currently not supported and probably never will, but that should not stop you, as variants are immutable and have by-value comparison, just like records.\n\nThe `VariantOf` method is how you tell the generator what the possible values of this variant are. Anything that is a valid parameter and field is also a valid option here and the parameter names will be used as hints throughout the generated interface. Do not use `out`, `in` or `ref` modifiers, as those are reserved for future use.\n\n`MyVariant` will receive a rich set of public properties and methods for you to enjoy. In addition you will find a private `_variant` field which hides away all the implementation details. If you chose to add your own custom members to `MyVariant` you may safely access this field.\n\nAny constraints you put on the type parameters will be taken into consideration and affect the generated code.\n\n**Note**: The .NET runtime forbids layout manipulation on generic types, so in the above example `MyVariant` will occupy less memory than `MyVariant\u003cint, double, string\u003e` despite seemingly having the same content. Be aware of this when using generic variants and try to use concrete types whenever possible.\n\n### Using a Variant\n\nWith the above declaration, you are ready to use your new variant:\n\n```csharp\nvar variant1 = new MyVariant(1);\nvariant1.Match(out int i);\nConsole.WriteLine(i); // prints 1\n\nvar variant2 = new MyVariant(2.5);\nvariant2.Match(out double d);\nConsole.WriteLine(d); // prints 2.5\n\nvar variant3 = new MyVariant(\"hello\");\nvariant3.Match(out string s);\nConsole.WriteLine(s); // prints \"hello\"\n\nMyVariant variant4 = 42; // implicitly create from accepted value type\nvoid Foo(MyVariant x) { }\nFoo(\"a string\"); // implicitly create MyVariant instance\n```\n\nNote how we used the same type to store and retrieve different types of values. However, you are not limited to just `out` variables, you can also pass in functions:\n\n```csharp\nvar variant1 = new MyVariant(1);\nvariant1.Match((int i) =\u003e Console.WriteLine(i)); // prints 1\n\nvar variant2 = new MyVariant(2.5);\nvariant2.Match((double d) =\u003e Console.WriteLine(d)); // prints 2.5\n\nvar variant3 = new MyVariant(\"world\");\nvariant3.Match((string s) =\u003e Console.WriteLine(s)); // prints \"world\"\n```\n\nAnd you can even return values from these functions, which get piped through `Match`:\n\n```csharp\nvar variant1 = new MyVariant(2);\nvar i = variant1.Match((int x) =\u003e x * 5); // i = 10\n\nvar variant2 = new MyVariant(2.5);\nvar d = variant2.Match((double x) =\u003e Math.Sin(x)); // d = 0.90929742682568171\n\nvar variant3 = new MyVariant(\"world\");\nvar s = variant3.Match((string x) =\u003e $\"hello {x}!\"); // s = \"hello world!\"\n```\n\nWhat happens if you try to retrieve a value from a variant it currently does not contain? It throws an `InvalidOperationException`. To avoid this there are overloads of `Match` and `TryMatch` giving you tools to avoid this disappointing outcome:\n\n```csharp\nvar variant = new MyVariant(\"not an int\");\n\nvariant.Match(out int i); // throws InvalidOperationException\nvariant.Match((int x) =\u003e x); // throws InvalidOperationException\n\nvar b1 = variant.TryMatch(out int i); // b1 = false, i = default\nvar b2 = variant.TryMatch(out string s); // b2 = true, s = \"not an int\"\n\nvar i = variant.Match((int x) =\u003e x, 42); // i = 42\nvar j = variant.Match((int x) =\u003e x, () =\u003e 1337); // j = 1337\n```\n\nUntil now all you could do was get a single type of value out of the variant using `Match` or `TryMatch`, and these two functions are designed to do only that. The real power behind variants, however, comes from visitation, where you provide a delegate to handle each possibility.\n\n```csharp\nstring GetContainedType(MyVariant variant)\n{\n  return variant.Visit(\n      i =\u003e \"int\",\n      d =\u003e \"double\"\n      s =\u003e \"string\");\n}\nGetContainedType(12); // returns \"int\"\nGetContainedType(3.14); // returns \"double\"\nGetContainedType(\"blubb\"); // returns \"string\"\n```\n\n`Visit` accepts one delegate per possible type it _might_ contain, and at runtime invokes the one corresponding to the value it _does_ contain. Naturally, all delegates must return the same type.\n\nThere are many available overloads of `Match` and `Visit` which hopefully help you achieve your goal in every scenario.\n\n### Custom Value Types\n\nOf course you are not restricted to just using builtin types like `int` or `double`. Any type that is valid for fields and parameters is valid for variants. A useful pattern is to declare your own types nested to the variant.\n\n```csharp\n[Variant]\nreadonly partial struct MyAdvancedVariant\n{\n    static partial void VariantOf(Option1 first, Option2 second, Option3 third);\n    \n    public readonly struct Option1\n    {\n        public int Value { get; }\n        public Option1(int value) { Value = value; }\n    }\n    public readonly struct Option2 { ... }\n    public class Option3 { ... }\n}\nMyAdvancedVariant v = new MyAdvancedVariant.Option1(13); // implicitly converts to MyAdvancedVariant\n```\n\n### Nullability\n\nThe generator fully supports nullability annotations. The generated source code honors the nullability context of where the class is defined and its generated interface will match the nullability annotations of the `VariantOf` parameters.\n\n```csharp\n#nullable enable\n\n[Variant]\npartial class Variant1 // code generated with #nullable enable\n{\n    static partial void VariantOf(int a, string s); // s is non-null in all generated code\n}\n\n[Variant]\npartial class Variant2 // code generated with #nullable enable\n{\n    static partial void VariantOf(int a, string? s); // s is nullable in all generated code\n}\n\n[Variant]\npartial class Variant3\u003cT\u003e // code generated with #nullable enable\n    where T : class\n{\n    // Even though T is constrained to not-null reference types,\n    // the actual value in the variant is nullable.\n    static partial void VariantOf(int i, T? t);\n}\n\n#nullable disable\n\n[Variant]\npartial class Variant4 // code generated with #nullable disable\n{\n    static partial void VariantOf(int a, string s); // s is nullable in all generated code\n}\n```\n\nAnd of course nullable value types are also supported.\n\n```csharp\n[Variant]\npartial class SomeVariant\n{\n    static partial void VariantOf(int? a, string s); // OK\n}\n```\n\n### Emptiness\n\nIf you declare your variant as a `struct`-type, you need to be aware that a variant can be _empty_, meaning it does not hold _any_ value. This is an unfortunate consequence of value types always having a default constructor in .NET. A `class` variant should never be empty unless you define your own constructor and default-construct the private `_variant` field. Use the public `IsEmpty` property to check for emptiness. Attempting to retrieve a value out of an empty variant results in a `InvalidOperationException`, however there are overloads of `Match` and `Visit` with ways to deal with emptiness in a more fluid manner.\n\n```csharp\n[Variant]\npartial struct MyStructVariant\n{\n    static partial void VariantOf(int first, string second?, byte[] third);\n}\n\nvar variant = default(MyStructVariant);\nvariant.IsEmpty; // true\nvariant.Match(out int i); // throws InvalidOperationException\nvar i = variant.Match(x =\u003e i + 1, 0); // i = 0\n\nvariant.Match(\n    x =\u003e \"first\",\n    x =\u003e \"second\",\n    x =\u003e \"third\",\n    () =\u003e \"empty\"); // Fourth option called when empty\n```\n\n## Generated Code Features\n\nThe generated implemenation provides some additional features depending on the types you provide it, or third-party libraries available to you.\n\n### `IDisposable` Support\n\nIf _at least one_ of the types included in the `VariantOf()` parameters implements `System.IDisposable`, or is a type parameter with a transitive `System.IDisposable` constraint, then the generated variant will also implement this interface and provide a public `Dispose()` member which delegates to the stored value's `Dispose()` if applicable.\n\nIf there already exists an implementation of `IDisposable.Dispose()` (either you defined one, or it is present in a base class) then the public `Dispose()` method is _not_ generated and it is your responsibility to take care of calling the private `_variant.Dispose()`.\n\n### External Integrations\n\nIf your type is declared in such a way that providing extensions methods is possible you will get additional integration with .NET facilities, or popular external libraries, listed in this section. The visibility (`public` or `internal`) of the extension methods is made to match the accessibility of your type declaration.\n\nThe `static class` containing all extension methods is by default generated in the same namespace containing the variant type, but that is configurable (see [Extension Class Namespace](#extension-class-namespace)).\n\n#### `IEnumerable\u003cT\u003e`\n\nThese allow for easy and powerful integration into `System.Linq`-like queries on `IEnumerable\u003cT\u003e` sequences, that let you manipulate a stream of variants based on the contained type.\n\n```csharp\n[Variant]\npublic readonly partial struct MyVariant\n{\n    static partial void VariantOf(int i, double d, string s);\n}\n\nvar xs = new MyVariant[] { 1, 2.0, \"3\", 4, 5.0, \"6\" };\n\n// Unary Match only transforms the matching type and drops all others\nxs.Match((int i) =\u003e i); // result: IEnumerable\u003cint\u003e [1, 4]\n\n// Binary Match lets you provide a fallback value or delegate to replace non-matching values with\nxs.Match((int i) =\u003e i, 0); // result: IEnumerable\u003cint\u003e [1, 0, 0, 4, 0, 0]\nxs.Match((int i) =\u003e i, () =\u003e -1); // result: IEnumerable\u003cint\u003e [1, -1, -1, 4, -1, -1]\n\n// Visit transform each possible value type individually\nxs.Visit(\n    i =\u003e $\"int {i}\",\n    d =\u003e $\"double {d}\"\n    s=\u003e $\"string {s}\");\n// result: IEnumerable\u003cstring\u003e [\"int 1\", \"double 2\", \"string 3\", \"int 4\", \"double 5\", \"string 6\"]\n```\n\n#### `IObservable\u003cT\u003e`\n\nThese allow for easy and powerful integration into `System.Reactive.Linq`-like queries on `IObservable\u003cT\u003e` sequences, that let you manipulate an asynchronous stream of variants based on the contained type.\n\n```csharp\n[Variant]\npublic readonly partial struct MyVariant\n{\n    static partial void VariantOf(int i, double d, string s);\n}\n\nvar xs = new MyVariant[] { 1, 2.0, \"3\", 4, 5.0, \"6\" }.ToObservable();\n\n// Unary Match only transforms the matching type and drops all others\nxs.Match((int i) =\u003e i); // result: IObservable\u003cint\u003e [1, 4]\n\n// Binary Match lets you provide a fallback value or delegate to replace non-matching values with\nxs.Match((int i) =\u003e i, 0); // result: IObservable\u003cint\u003e [1, 0, 0, 4, 0, 0]\nxs.Match((int i) =\u003e i, () =\u003e -1); // result: IObservable\u003cint\u003e [1, -1, -1, 4, -1, -1]\n\n// Visit transform each possible value type individually\nxs.Visit(\n    i =\u003e $\"int {i}\",\n    d =\u003e $\"double {d}\"\n    s=\u003e $\"string {s}\");\n// result: IObservable\u003cstring\u003e [\"int 1\", \"double 2\", \"string 3\", \"int 4\", \"double 5\", \"string 6\"]\n\n// VisitMany splits the sequence into multiple customizable sub-sequences which are then merged into one\nxs.VisitMany(\n    i =\u003e i.Where(ix =\u003e ix \u003e 1).Select(ix =\u003e $\"int {ix}\"),\n    d =\u003e d.Delay(dx =\u003e dx * 1000).Select(dx =\u003e $\"double {dx}\"),\n    s =\u003e s.Zip(Observable.Interval(100), (sx, _) =\u003e $\"string {sx}\");\n// results with timestamps: IObservable\u003cstring\u003e [\n//   \"int 4\" @0,\n//   \"string 3\" @100,\n//   \"string 6\" @200,\n//   \"double 2\" @2000,\n//   \"double 5\" @5000,\n// ]\n\n// Altenatively VisitMany allows you to transform and combine the split streams however you want.\nxs.VisitMany((i, d, s) =\u003e CombineLatest(i, d, s, (ix, dx, sx) =\u003e (ix, dx, sx));\n// results: IObservable\u003cstring\u003e [\n//   (1, 2.0, \"3\"),\n//   (4, 2.0, \"3\"),\n//   (4, 5.0, \"3\"),\n//   (4, 5.0, \"6\"),\n// ]\n```\n\n## Customization\n\nAn overview of how you can customize the generated source code.\n\n### Extension Class Namespace\n\nAs mentioned in [Third-party Integrations](#third-party-integrations) if the circumstances are right extension methods for integration with third-party libraries can be generated. By default the accompanying `static class` is put in the namespace containing the variant type.\n\n```csharp\n// Your declaration\nnamespace Foo.Bar.Baz\n{\n  [Variant]\n  internal partial class MyVariant\n  {\n    static partial void VariantOf(int i, double d, string s);\n  }\n}\n// Generated code\nnamespace Foo.Bar.Baz\n{\n  partial class MyVariant { /* variant implementation */ }\n  \n  internal static class _MyVariant_Ex { /* all extension methods for MyVariant go here */ }\n}\n```\n\nHowever this means the extension methods are only accessible if you are inside namespace `Foo.Bar.Baz` or have `using Foo.Bar.Baz;` active in your scope. Thus if you are in namespace `Foo.Bar` and are handled a `IEnumerable\u003cFoo.Bar.Baz.MyVariant\u003e` then the extension methods won't be visible to you. If this is not what you want you can set a MSBuild property to change the namespace where all extension classes are generated (an additional per-class option is planned) to whichever place you put common extension methods. I highly recomment making them visible everywhere, you don't want to miss out on them!\n\n```xml\n\u003cPropertyGroup\u003e\n  \u003cdotVariant-ExtensionClassNamespace\u003eFoo.Extensions\u003c/dotVariant-ExtensionClassNamespace\u003e\n\u003c/PropertyGroup\u003e\n```\n\n## Compatibility\n\n- To use the generator you must use the latest .NET SDK\n- The generated code is compatible down to C# `7.3` and adjusts itself to the available language version and runtime facilities.\n- The required runtime support library targets `netstandard1.0`.\n\n## License\n\nLicensed under the [Boost Software License 1.0](LICENSE.txt).\n","funding_links":[],"categories":["Source Generators","Do not want to test 112 ( old ISourceGenerator )"],"sub_categories":["Functional Programming","1. [ThisAssembly](https://ignatandrei.github.io/RSCG_Examples/v2/docs/ThisAssembly) , in the [EnhancementProject](https://ignatandrei.github.io/RSCG_Examples/v2/docs/rscg-examples#enhancementproject) category"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmknejp%2Fdotvariant","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmknejp%2Fdotvariant","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmknejp%2Fdotvariant/lists"}