Created
April 26, 2018 11:58
-
-
Save awright18/fd181f67d917c0f371d61ab6e44c7daf to your computer and use it in GitHub Desktop.
Functional Result in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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