Created
February 11, 2018 09:43
-
-
Save Harunx9/94e0473fd41e749431cb1a3b266d0917 to your computer and use it in GitHub Desktop.
Test optional monad 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 IOptional<T> where T : class | |
{ | |
T Value { get; } | |
} | |
public abstract class Optional<T> : IOptional<T> | |
where T : class | |
{ | |
public abstract T Value { get; } | |
public static IOptional<T> Some(T value) => new Some<T>(value); | |
public static IOptional<T> None() => new None<T>(); | |
} | |
public sealed class Some<T> : Optional<T> | |
where T : class | |
{ | |
public override T Value { get; } | |
public Some(T value) | |
{ | |
Value = value; | |
} | |
} | |
public sealed class None<T> : Optional<T> | |
where T : class | |
{ | |
public override T Value => throw new NotSupportedException(); | |
} | |
class Person | |
{ | |
public Person(string name, string surname) | |
{ | |
Name = name; | |
Surname = surname; | |
} | |
public string Name { get; set; } | |
public string Surname { get; set; } | |
} | |
class Program | |
{ | |
public static IOptional<Person> GetPerson(bool isSome) | |
=> isSome ? | |
Optional<Person>.Some(new Person("Adam", "Kowalski")) : | |
Optional<Person>.None(); | |
static void Main(string[] args) | |
{ | |
var opt = GetPerson(false); | |
switch (opt) | |
{ | |
case Some<Person> p: | |
Console.WriteLine($"{p.Value.Name} {p.Value.Surname} is present"); | |
break; | |
case None<Person> n: | |
Console.WriteLine("No one is present"); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment