N.SourceGenerators.UnionTypes 0.17.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package N.SourceGenerators.UnionTypes --version 0.17.0
                    
NuGet\Install-Package N.SourceGenerators.UnionTypes -Version 0.17.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="N.SourceGenerators.UnionTypes" Version="0.17.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="N.SourceGenerators.UnionTypes" Version="0.17.0" />
                    
Directory.Packages.props
<PackageReference Include="N.SourceGenerators.UnionTypes" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add N.SourceGenerators.UnionTypes --version 0.17.0
                    
#r "nuget: N.SourceGenerators.UnionTypes, 0.17.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package N.SourceGenerators.UnionTypes@0.17.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=N.SourceGenerators.UnionTypes&version=0.17.0
                    
Install as a Cake Addin
#tool nuget:?package=N.SourceGenerators.UnionTypes&version=0.17.0
                    
Install as a Cake Tool

N.SourceGenerators.UnionTypes

Discriminated union type source generator

Motivation

C# doesn't support discriminated unions yet. This source generator helps automate writing union types with set of helper methods.

Getting Started

Add package reference to N.SourceGenerators.UnionTypes

dotnet add package N.SourceGenerators.UnionTypes

Create a partial class or struct that will be used as a union type

public partial class FooResult
{
}

Add types you want to use in a discriminated union

public record Success(int Value);
public record ValidationError(string Message);
public record NotFoundError;

public partial class FooResult
{
}

Add N.SourceGenerators.UnionTypes.UnionTypeAttribute to a union type.

using N.SourceGenerators.UnionTypes;

public record Success(int Value);
public record ValidationError(string Message);
public record NotFoundError;

[UnionType(typeof(Success))]
[UnionType(typeof(ValidationError))]
[UnionType(typeof(NotFoundError))]
public partial class FooResult
{
}

Examples

All examples can be found in examples project

Implicit conversion

public FooResult ImplicitReturn()
{
    // you can return any union type variation without creating FooResult
    return new NotFoundError();
}

Explicit conversion

public ValidationError ExplicitCast(FooResult result)
{
    return (ValidationError)result;
}

Checking value type

public void ValueTypeProperty()
{
    FooResult foo = GetFoo();
    Type valueType = foo.ValueType; // returns typeof(NotFoundError)

    static FooResult GetFoo()
    {
        return new NotFoundError();
    }
}

TryGet method is used to check if union contains a specific type

public void TryGetValue()
{
    FooResult foo = GetFoo();
    if (foo.TryGetNotFoundError(out var notFoundError))
    {
        // make something with notFoundError
    }

    static FooResult GetFoo()
    {
        return new NotFoundError();
    }
}

Alias for each variant is generated based on type name. Use alias parameter to override it.

[UnionType(typeof(int))]
[UnionType(typeof(string))]
// default alias is 'ArrayOfTupleOfIntAndString' but it is overriden by alias parameter
[UnionType(typeof(Tuple<int,string>[]), alias: "Items")]
public partial class AliasResult
{
}

Match and MatchAsync methods are used to convert union type to another type. These methods force you to handle all possible variations.

public IActionResult MatchMethod(FooResult result)
{
    return result.Match<IActionResult>(
        success => new OkResult(),
        validationError => new BadRequestResult(),
        notFoundError => new NotFoundResult()
    );
}

public async Task<IActionResult> MatchAsyncMethod(FooResult result, CancellationToken cancellationToken)
{
    return await result.MatchAsync<IActionResult>(
        static async (success, ct) =>
        {
            await SomeWork(success, ct);
            return new OkResult();
        }, static async (validationError, ct) =>
        {
            await SomeWork(validationError, ct);
            return new BadRequestResult();
        }, static async (notFoundError, ct) =>
        {
            await SomeWork(notFoundError, ct);
            return new NotFoundResult();
        }, cancellationToken);

    static Task SomeWork<T>(T value, CancellationToken ct)
    {
        return Task.Delay(100, ct);
    }
}

Switch and SwitchAsync methods are used to execute some work based on inner type

 public void SwitchMethod(FooResult result)
{
    result.Switch(
        success => SomeWork(success),
        validationError => SomeWork(validationError),
        notFoundError => SomeWork(notFoundError)
    );

    static void SomeWork<T>(T value)
    {
        throw new NotImplementedException();
    }
}

public async Task SwitchAsyncMethod(FooResult result, CancellationToken cancellationToken)
{
    await result.SwitchAsync(
        static async (success, ct) =>
        {
            await SomeWork(success, ct);
        }, static async (validationError, ct) =>
        {
            await SomeWork(validationError, ct);
        }, static async (notFoundError, ct) =>
        {
            await SomeWork(notFoundError, ct);
        }, cancellationToken);

    static Task SomeWork<T>(T value, CancellationToken ct)
    {
        return Task.Delay(100, ct);
    }
}
There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

  • .NETStandard 2.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on N.SourceGenerators.UnionTypes:

Package Downloads
Zomp.SyncMethodGenerator

Generates synchronized method from async method

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.28.0 16,959 5/2/2024
0.28.0-rc.61 75 5/2/2024
0.28.0-rc.60 48 5/2/2024
0.27.0 1,711 3/19/2024
0.27.0-rc.58 102 3/19/2024
0.27.0-rc.57 129 3/13/2024
0.26.0 63,455 10/26/2023
0.26.0-rc.55 111 11/16/2023
0.26.0-rc.53 122 10/30/2023
0.26.0-rc.52 93 10/30/2023
0.26.0-rc.51 105 10/30/2023
0.26.0-rc.50 91 10/30/2023
0.26.0-rc.48 134 10/26/2023
0.25.3 419 10/18/2023
0.25.3-rc.41 107 10/18/2023
0.25.1-rc.40 359 10/17/2023
0.25.0-rc.39 118 10/17/2023
0.24.0 1,076 10/17/2023
0.24.0-rc.37 175 10/16/2023
0.23.0 761 10/3/2023
0.23.0-rc.35 336 10/2/2023
0.22.0 370 10/2/2023
0.22.0-rc.33 106 10/2/2023
0.21.0 333 10/2/2023
0.21.0-rc.31 131 10/2/2023
0.21.0-rc.30 109 9/28/2023
0.20.0-rc.29 951 9/6/2023
0.20.0-rc.28 129 9/6/2023
0.19.0 744 8/3/2023
0.18.0 617 2/5/2023
0.17.0 455 2/2/2023
0.16.0 426 1/30/2023
0.15.0 463 1/29/2023
0.14.0 449 1/21/2023
0.13.0 497 1/20/2023
0.12.0 494 1/20/2023
0.11.0 467 1/18/2023
0.10.0 497 1/18/2023
0.9.0 491 1/17/2023
0.8.0 444 1/17/2023
0.7.0 456 1/17/2023
0.6.0 466 1/15/2023
0.5.1 458 1/15/2023
0.5.0 474 1/15/2023
0.4.0 516 1/15/2023
0.3.0 536 1/15/2023
0.2.0 525 1/15/2023
0.1.0 567 1/15/2023