Skip to content
/ Unions Public

This package provides Discriminated Unions for C# with an opportunity inherit from built in type and create custom Union Type.

License

Notifications You must be signed in to change notification settings

iQweex/Unions

Repository files navigation

Qweex.Unions

Build status NuGet

Create custom union type

public class ParsedInt : TUnion<int, Error>
{
    public ParsedInt(string str) 
        : this(() =>
        {
            int a;
            return int.TryParse(str, out a) ? 
                new ParsedInt(a) 
              : 
                new ParsedInt(new Error("Invalid Input"));
        }) {}
        
    // you can generate all ctors with VS, 
    // because TUnion<,> is an abstract class, not interface, and it has own ctors
    // which require overloads
    public ParsedInt(Func<TUnion<int, Error>> factory) : base(factory) {}
    public ParsedInt(int value) : base(value) {}
    public ParsedInt(Error value) : base(value) {}
}

And use it

Assert
    .Equal(
        "27",
        new ParsedInt("27")
            .Match(
                i => i.ToString(),
                e => e.Message
            )
    );

Assert
    .Equal(
        "Invalid Input",
        new ParsedInt("a27")
            .Match(
                i => i.ToString(),
                e => e.Message
            )
    );

About

This package provides Discriminated Unions for C# with an opportunity inherit from built in type and create custom Union Type.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages