
c# maybe implementation
By: a guest on
Oct 27th, 2012 | syntax:
C# | size: 1.10 KB | hits: 44 | expires: Never
public struct Maybe<T> where T : class
{
T Value;
public static Maybe<T> Just(T t)
{
return new Maybe<T>() { Value = t };
}
public static Maybe<T> Nothing { get { return new Maybe<T>(); } }
public static implicit operator Maybe<T>(T value)
{
return new Maybe<T>() { Value = value };
}
public void Guard(Action<T> valuePresent, Action valueAbsent)
{
if (Value != null)
{
if (valuePresent != null)
valuePresent(Value);
}
else if (valueAbsent != null) valueAbsent();
}
public TResult Guard<TResult>(Func<T, TResult> valuePresent, Func<TResult> valueAbsent)
{
if (Value != null)
{
if (valuePresent != null)
return valuePresent(Value);
}
else if (valueAbsent != null) return valueAbsent();
throw new ArgumentException("A Maybe guard case was missing and hit");
}
}