Skip to content

Instantly share code, notes, and snippets.

@andresmoschini
Last active August 29, 2015 14:26
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 andresmoschini/d5dfca8ac46ba3e4d8d5 to your computer and use it in GitHub Desktop.
Save andresmoschini/d5dfca8ac46ba3e4d8d5 to your computer and use it in GitHub Desktop.
Maybe Monad C# implementation
using System;
using System.Collections;
using System.Collections.Generic;
namespace Utilities
{
public static class Maybe
{
public static Maybe<T> From<T>(T value) => new Maybe<T>(value);
public static Maybe<T> None<T>() => default(Maybe<T>);
}
public struct Maybe<T> : IEnumerable<T>
{
readonly bool _hasValue;
public bool HasValue => _hasValue;
readonly T _value;
public T Value
{
get
{
if (!_hasValue)
{
throw new InvalidOperationException();
}
return _value;
}
}
internal Maybe(T value)
{
_hasValue = !ReferenceEquals(value, null);
_value = value;
}
public static implicit operator Maybe<T>(T value) => new Maybe<T>(value);
public IEnumerator<T> GetEnumerator()
{
if (_hasValue)
{
yield return _value;
}
yield break;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment