Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Created September 7, 2022 12:04
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 petitviolet/d29d7cd4d3f967ebda06a7b429d05070 to your computer and use it in GitHub Desktop.
Save petitviolet/d29d7cd4d3f967ebda06a7b429d05070 to your computer and use it in GitHub Desktop.
Result type to hold a result of either success or failure in Unity C#
using System;
namespace MyNamespace
{
/// holds an either succeeded or failed result
// need latest C# version to use <out T, out E> instead
public interface Result<T, E> where E : Exception
{
public bool OK { get; }
public static Failure<T, E> Failed(E error)
{
return new Failure<T, E>(error);
}
public static Success<T, E> Succeeded(T content)
{
return new Success<T, E>(content);
}
// Fold without returning a value
public void OnComplete(Action<T> onSuccess, Action<E> onFailure)
{
Fold<bool>(t => { onSuccess(t); return true; }, t => { onFailure(t); return false; });
}
public R Fold<R>(Func<T, R> onSuccess, Func<E, R> onFailure);
}
public class Failure<T, E> : Result<T, E> where E : Exception
{
public bool OK
{
get { return false; }
}
public readonly E Error;
internal Failure(E error)
{
Error = error;
}
public R Fold<R>(Func<T, R> onSuccess, Func<E, R> onFailure)
{
return onFailure(Error);
}
}
public class Success<T, E> : Result<T, E> where E : Exception
{
public readonly T Content;
public bool OK
{
get { return true; }
}
internal Success(T content)
{
Content = content;
}
public R Fold<R>(Func<T, R> onSuccess, Func<E, R> onFailure)
{
return onSuccess(Content);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment