OptionTypes 1.3.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package OptionTypes --version 1.3.0
                    
NuGet\Install-Package OptionTypes -Version 1.3.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="OptionTypes" Version="1.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OptionTypes" Version="1.3.0" />
                    
Directory.Packages.props
<PackageReference Include="OptionTypes" />
                    
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 OptionTypes --version 1.3.0
                    
#r "nuget: OptionTypes, 1.3.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 OptionTypes@1.3.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=OptionTypes&version=1.3.0
                    
Install as a Cake Addin
#tool nuget:?package=OptionTypes&version=1.3.0
                    
Install as a Cake Tool

NuGet NuGet

OptionTypes

Contents

Description

OptionTypes is a package to use some useful monads in C#. It contains 2 classes:

  • The Maybe<T> class allows to create an item of type T that may have no value. This value cannot be accessed in an unsafe manner by design, making really easy to completely remove null references from your code and reducing the number of NullReferenceException exceptions thrown.

  • The Result class represents an operation that has been completed. This reduces the number of try/catch blocks needed to manage application flow, making error management explicit and ending with more reliable code.

Usage

Unit

Unit is a helper type to represent the absence of value (think of it as void). Because in functional programming every function returns a value, it is added here for compatibility.

Maybe

Create a new Maybe using one of the helper methods (Maybe.FromValue, Maybe.Some, and Maybe.None):

var maybeInt = Maybe.Some(1);
var maybeFloat = Maybe.FromValue(12);
string? nullableString = null;
var maybeString = Maybe.FromValue(nullableString);

Map its content using the Map method:

var maybeText = await ReadTextFromFile(filePath);

var uppercaseText = maybeText.Map(text => text.ToUpper());

You can also map to another Maybe and it will be flatten:

var number = Maybe.FromValue(1);

// double type is Maybe<int>
var double = number.Map(x => Maybe.FromValue(x * 2));

If you want to check both options, use the Match method:

let user = await GetUser();


var userName = user.Match(x => x.Name, () => "User not found");

In case you want to provide a fallback value, you can use ValueOr:

var maybeUserName = await GetUserName();
var userName = maybeUserName.ValueOr("Unknown user");

In case you want to do something if there is no value present, you can use the IsNone method:

Maybe<User> maybeUser = await GetUser();

if(maybeUser.IsNone(out User user))
{
    return Results.NotFound();
}

var posts = postService.GetPostsByUserId(user.Id);

NOTE: There is no IsSome method and it is not planned. This method was added to allow for early returns when needed (like the example).

You can force the value out using the Unwrap method. This approach is not recommended:

var maybeValue = Maybe.Some(1);

var value = maybeValue.Unwrap() // 1

var maybeString = Maybe<string>.None();
maybeString.Unwrap(); // throws NullReferenceException

There are also extension methods for Task<Maybe<T>> so you can chain Map, Match, ValueOr, and Unwrap to your tasks.

var userBalance = GetUser() // GetUser returns a Task<Maybe<User>>
                    .Map(user => bankService.GetAccounts(user.Id))
                    .Map(accounts => accounts.Sum(a => a.Balance))
                    .ValueOr(0m);

Result

You can create an instance using the Ok/Err static methods:

var okResult = Result<Unit, ProcessError>.Ok(default);
var errorResult = Result<Unit, ProcessError>.Err(ProcessError.DatabaseConnection);

You can map the ok value or err value using Map and MapErr methods:

var okResult = Result<int, Exception>.Ok(3).Map(x => x*2)); // Ok(6)
var errResult = Result<Unit, string>.Err("failure").MapErr(x => x.ToUpper()); // Err("FAILURE")

To provide handlers for both cases, which should be the normal usage, use the Match method:

var result = await CreateUser();

result.Match(
    user => Results.Created("/user", { id: user.Id }),
    err => err switch {
        CreateUserError.EmailExists => Results.Conflict(),
        _ => Results.BadRequest()
    });

Sometimes you only want to know if an operation has completed successfully to get the ok value. You can use the Ok method:

var parsingResult = ParseLines(path);

var linesParsed = parsingResult.Ok().ValueOr(0);

Console.WriteLine($"Parsed {linesParsed} lines");

In order to get early returns when needed, there is an IsErr method:

Result<User, string> userCreationResult = await CreateUser(userPayload);

if (userCreationResult.IsErr(out User user, out string error))
{
    return Result<Unit, UserCreationError>.Err(UserCreationError.CannotCreateUser);
}

var userRoleResult = await AssignRoles(user, Roles.Admin);

if (userRoleResult.IsErr(out var roleError)) 
{
    return Result<Unit, UserCreationError>.Err(UserCreationError.CannotAssignRole);
}

emailService.NotifyUser(user.Email);

As with Maybe, there are some extensions in Task to be able to chain methods:

public async IResult Post([FromBody] UserPayload payload)
    => await CreateUser(payload).Match<IResult>(
        user => Results.Created("/user", { id: user.Id }),
        err => err switch {
            CreateUserError.EmailExists => Results.Conflict(),
            _ => Results.BadRequest()
        });

Design philosophy

The idea behind this small package was to provide Option/Maybe/Result monads that work idiomatically with C#, whithout losing the essence of them.

In order to achieve this, an approach of Explicit better than implicit was used:

  • When working with Maybe, minimize the posibility of NullReferenceException by limiting the options to get the value out, enforcing the developer to handle all the cases.
  • When working with Result, minimize the risk of unforseen consequences (λ) by encouraging to use the Match statement.
  • Encourage the usage of Error values, let it be records with some payload or enums, that provide useful information and force the developer to take action for each one of them. By being explicit in what kind of errors can pop out, the developer is forced to handle all the cases than can go wrong and not rely on catch blocks.

What's missing

Because of the limitations of C#, some things cannot be achieved. Here's a small list:

  • In order to create a Result, both types should be specified. This is annoying, because when you are using large class names, you end up doing:
    public async Task<Result<CreateUserReturnValue, CreateUserError>> CreateUser(CreateUserPayload payload)
    {
    ...
        if (**somecondition**)
        {
            return Result<CreateUserReturnValue, CreateUserError>.Err(...);
        }
    ...
    }
    
    This can be mitigated by using using alias like this:
    using CreateUserResult = OptionTypes.Result<UseCases.CreateUserReturnValue, UseCases.CreateUserError>;
    
    public async Task<CreateUserResult> CreateUser(CreateUserPayload payload)
    {
    ...
        if (**somecondition**)
        {
            return CreateUserResult.Err(...);
        }
    ...
    }
    
  • Result<Unit, _> feels weird, as you have to manually do Result<Unit, _>.Ok(default) or Result<Unit, _>.Ok(new Unit()). No workaround for this I'm afraid.
  • Early returns feel off. I would've loved to have something similar to Rust's question mark, but Maybe.IsNone and Result.IsErr are the closest things I could think of.
  • The absence of union types/discriminated unions/closed enums make managing the different options underwhelming and unreliable if you are not careful. If you have a method like this:
enum ProcessError
{
    FailureA,
    FailureB
}

Result<Unit, ProcessError> DoProcess() { ... }

public void Run() 
{
    var result = DoProcess();

    result.Match(_ => Console.WriteLine("Success"),
    err => err switch
    {
        ProcessError.FailureA => Console.WriteLine("FailureA"),
        ProcessError.FailureB => Console.WriteLine("FailureB"),
    });
}

You may think that you are handling everything, as the enum only has 2 options, but you would receive a warning. This is because enums are int in C#, so you could do (ProcessError)435627 and pass. Their proposed solution is to add a general case _ => WHATEVER but this is exactly what this library is trying to avoid. Again, the goal is to be explicit, because if you add a default case, you will not receive a warning nor an error when you add another error in ProcessError. So the only option for now is to disable the rule. Ending like this:

enum ProcessError
{
    FailureA,
    FailureB
}

Result<Unit, ProcessError> DoProcess() { ... }

public void Run() 
{
    var result = DoProcess();

    result.Match(_ => Console.WriteLine("Success"),
    #pragma warning disable CS8524 // The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value.
    err => err switch
    {
        ProcessError.FailureA => Console.WriteLine("FailureA"),
        ProcessError.FailureB => Console.WriteLine("FailureB"),
    });
    #pragma warning restore CS8524 // The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value.
}

Usage inside Entity Framework Core

This uses the internal EF Api

The project OptionTypes.Ef contains the ValueConverters needed to map the Maybe<T> type to the Entity Framework columns.

In the OnModelCreating method overriden in your DbContext, call AddOptionTypeConverters. This will add all the converters needed in your model.

Product 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 is compatible.  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 is compatible. 
.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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.
  • .NETStandard 2.1

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on OptionTypes:

Package Downloads
OptionTypes.Ef

Value converters for EntityFramework to convert to OptionTypes

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.4.0 160 3/13/2025
1.3.0 120 12/19/2024
1.2.0 171 8/22/2024
1.1.0 240 11/17/2023
1.0.5 120 11/16/2023
1.0.4 128 11/8/2023
1.0.3 120 11/7/2023
1.0.2 360 1/26/2023
1.0.1 307 1/26/2023