Skip to content

Instantly share code, notes, and snippets.

@einarwh
Last active January 17, 2017 14:01
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 einarwh/77445006d6f72c16d3d441a627c0bd5b to your computer and use it in GitHub Desktop.
Save einarwh/77445006d6f72c16d3d441a627c0bd5b to your computer and use it in GitHub Desktop.
Mayhaps value, mayhaps not.
public abstract class Mayhaps<T>
{
private Mayhaps() {}
public abstract bool HasValue { get; }
public abstract T Value { get; }
public abstract Mayhaps<TR> Map<TR>(Func<T, TR> f);
private class MayhapsValue : Mayhaps<T>
{
private readonly T _value;
public MayhapsValue(T value)
{
if (value == null) {
throw new ArgumentNullException("Begone, null!");
}
_value = value;
}
public override bool HasValue
{
get { return true; }
}
public override T Value
{
get { return _value; }
}
public override Mayhaps<TR> Map<TR>(Func<T, TR> f)
{
return Mayhaps<TR>.Indeed(f(_value));
}
}
private class MayhapsNothing : Mayhaps<T>
{
public override bool HasValue
{
get { return false; }
}
public override T Value
{ get { throw new InvalidOperationException("Nothing here."); } }
public override Mayhaps<TR> Map<TR>(Func<T, TR> f)
{
return Mayhaps<TR>.Nothing;
}
}
private static MayhapsNothing _nothing = new MayhapsNothing();
public static Mayhaps<T> Indeed(T value)
{
return new MayhapsValue(value);
}
public static Mayhaps<T> Nothing
{
get { return _nothing; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment