Skip to content

Instantly share code, notes, and snippets.

@Harunx9
Created February 11, 2018 09:43
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/94e0473fd41e749431cb1a3b266d0917 to your computer and use it in GitHub Desktop.
Save Harunx9/94e0473fd41e749431cb1a3b266d0917 to your computer and use it in GitHub Desktop.
Test optional monad with C# 7 pattern matching
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