Skip to content

Instantly share code, notes, and snippets.

@awright18
Created April 26, 2018 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awright18/fd181f67d917c0f371d61ab6e44c7daf to your computer and use it in GitHub Desktop.
Save awright18/fd181f67d917c0f371d61ab6e44c7daf to your computer and use it in GitHub Desktop.
Functional Result in C#
using System;
using System.Runtime.InteropServices.ComTypes;
namespace Result
{
public static class Result
{
public static Result<T,TError> Ok<T,TError>(T value)
{
return new Result<T,TError>(value);
}
public static Result<T,TError> Error<T,TError>(TError error)
{
return new Result<T,TError>(error);
}
public static Result<T2,TError> Bind<T, TError,T2>(this Result<T,TError> result, Func<T,T2> apply)
{
if (result.HasValue)
{
return Ok<T2,TError>(apply(result.Value));
}
return Error<T2,TError>(result.Error);
}
public static Result<T2,TError> MapError<T, TError,T2>(this Result<T, TError> result, Func<TError, T2> apply)
{
if (result.HasError)
{
return Ok<T2, TError>(apply(result.Error));
}
return null;
}
}
public class Result<TSuccess,TError>
{
public bool HasValue => Value != null;
public TSuccess Value {get;}
public TError Error{get;}
public bool HasError => Error != null;
internal Result(TSuccess success)
{
Value = success;
}
internal Result(TError error)
{
Error = error;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment