Skip to content

Instantly share code, notes, and snippets.

@dhilst
Created May 17, 2021 23:25
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 dhilst/b5759f889b719af1f6d37f2754d3ac26 to your computer and use it in GitHub Desktop.
Save dhilst/b5759f889b719af1f6d37f2754d3ac26 to your computer and use it in GitHub Desktop.
Result class in C#
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