Skip to content

Instantly share code, notes, and snippets.

@Harunx9
Last active February 11, 2018 10:09
Show Gist options
  • Save Harunx9/e972f3662ec2ed7ed376c49fda941502 to your computer and use it in GitHub Desktop.
Save Harunx9/e972f3662ec2ed7ed376c49fda941502 to your computer and use it in GitHub Desktop.
Result with Error monad test with C# 7 pattern matching
using System;
namespace MonadTest
{
public interface IResult<E>
{
E Error { get; }
}
public abstract class Result<E> : IResult<E>
{
public abstract E Error { get; }
public static IResult<E> Ok() => new Ok<E>();
public static IResult<E> Err(E error) => new Err<E>(error);
}
public sealed class Ok<E> : Result<E>
{
public override E Error => throw new NotSupportedException();
}
public sealed class Err<E> : Result<E>
{
public override E Error { get; }
public Err(E error)
{
Error = error;
}
}
class Program
{
public static IResult<string> GetResult(bool isOk)
{
return isOk ?
Result<string>.Ok():
Result<string>.Err("Ooops we got error");
}
static void Main(string[] args)
{
var res = GetResult(false);
switch (res)
{
case Ok<string> ok:
Console.WriteLine("Everything is fine");
break;
case Err<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