Skip to content

Instantly share code, notes, and snippets.

@Harunx9
Created February 11, 2018 10:40
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 Harunx9/ddd029364ab42da15e1aa3208f0d6598 to your computer and use it in GitHub Desktop.
Save Harunx9/ddd029364ab42da15e1aa3208f0d6598 to your computer and use it in GitHub Desktop.
using System;
namespace MonadTest
{
public interface IResult<T, E>
{
T Outcome { get; }
E Error { get; }
}
public abstract class Result<T, E> : IResult<T, E>
{
public abstract T Outcome { get; }
public abstract E Error { get; }
public static IResult<T, E> Ok(T outcome) => new Ok<T, E>(outcome);
public static IResult<T, E> Err(E error) => new Err<T, E>(error);
}
public sealed class Ok<T, E> : Result<T, E>
{
public override T Outcome { get; }
public override E Error => throw new NotSupportedException();
public Ok(T outcome)
{
Outcome = outcome;
}
}
public sealed class Err<T, E> : Result<T, E>
{
public override T Outcome => throw new NotSupportedException();
public override E Error { get; }
public Err(E error)
{
Error = error;
}
}
class Program
{
public static IResult<int,string> GetResult(bool isOk)
{
return isOk ?
Result<int, string>.Ok(1):
Result<int, string>.Err("Ooops we got error");
}
static void Main(string[] args)
{
var res = GetResult(true);
switch (res)
{
case Ok<int, string> ok:
Console.WriteLine($"Lucky number is {ok.Outcome}");
break;
case Err<int, string> err:
Console.WriteLine(err.Error);
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment