Created
May 17, 2021 23:25
-
-
Save dhilst/b5759f889b719af1f6d37f2754d3ac26 to your computer and use it in GitHub Desktop.
Result class 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; | |
namespace TodoApi | |
{ | |
/// <summary> | |
/// A generic result class that should enough | |
/// to get rid of exceptions and be general enough | |
/// for handling all kind of errors. | |
/// | |
/// User is forced to handle error case to get success | |
/// value. | |
/// | |
/// <example> | |
/// <code> | |
/// var result = Result<int, string>.Success(1); | |
/// string filtered = result.Match( | |
/// success => success.ToString(), | |
/// error => error, | |
/// ); | |
/// </code> | |
/// </example> | |
/// </summary> | |
public class Result<T, E> | |
{ | |
readonly T Val; | |
readonly E Err; | |
readonly bool IsSuccess; | |
bool IsError { get => !IsSuccess; } | |
protected Result(T val) | |
{ | |
Val = val; | |
IsSuccess = true; | |
} | |
protected Result(E error) | |
{ | |
Err = error; | |
IsSuccess = false; | |
} | |
public static Result<T, E> Success(T value) => | |
new Result<T, E>(value); | |
public static Result<T, E> Error(E error) => | |
new Result<T, E>(error); | |
public R Match<R>( | |
Func<T, R> SucFn, | |
Func<E, R> ErrFn) | |
{ | |
return IsSuccess ? SucFn(Val) : ErrFn(Err); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment