Last active
February 11, 2018 10:09
-
-
Save Harunx9/e972f3662ec2ed7ed376c49fda941502 to your computer and use it in GitHub Desktop.
Result with Error monad test with C# 7 pattern matching
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 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