Skip to content

Instantly share code, notes, and snippets.

@kseo kseo/Option.cs
Created Jan 19, 2015

Embed
What would you like to do?
Step by step implementation of Option type in C#
using System;
namespace Option
{
public abstract class Option<T>
{
public abstract T Value { get; }
public abstract bool IsSome { get; }
public abstract bool IsNone { get; }
public abstract Option<TResult> Map<TResult>(Func<T, TResult> func);
public abstract TResult Match<TResult>(Func<T, TResult> someFunc, Func<TResult> noneFunc);
}
public sealed class None<T> : Option<T>
{
public None()
{
}
public override T Value
{
get { throw new System.NotSupportedException("There is no value"); }
}
public override bool IsSome { get { return false; } }
public override bool IsNone { get { return true; } }
public override Option<TResult> Map<TResult>(Func<T, TResult> func)
{
return new None<TResult>();
}
public override TResult Match<TResult>(Func<T, TResult> someFunc, Func<TResult> noneFunc)
{
return noneFunc();
}
}
public sealed class Some<T> : Option<T>
{
private T value;
public Some(T value)
{
if (value == null)
{
throw new System.ArgumentNullException("value", "Some value was null, use None instead");
}
this.value = value;
}
public override T Value { get { return value; } }
public override bool IsSome { get { return true; } }
public override bool IsNone { get { return false; } }
public override Option<TResult> Map<TResult>(Func<T, TResult> func)
{
return new Some<TResult>(func(value));
}
public override TResult Match<TResult>(Func<T, TResult> someFunc, Func<TResult> noneFunc)
{
return someFunc(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.