Skip to content

Instantly share code, notes, and snippets.

@pragmatrix
Last active August 29, 2015 14:02
Show Gist options
  • Save pragmatrix/3a53c76e5783b3d43018 to your computer and use it in GitHub Desktop.
Save pragmatrix/3a53c76e5783b3d43018 to your computer and use it in GitHub Desktop.
ValueOrExeption
// see https://gist.github.com/mausch/2ef2e9b26a89d7594e3d
public struct ValueOrException<TValue>
{
public ValueOrException(TValue value, Exception exception)
{
_value = value;
_exception = exception;
}
readonly TValue _value;
readonly Exception _exception;
public static ValueOrException<TValue> Value(TValue v)
{
return new ValueOrException<TValue>(v, null);
}
public static ValueOrException<TValue> Exception(Exception e)
{
return new ValueOrException<TValue>(default(TValue), e);
}
public T Match<T>(Func<TValue, T> ifValue, Func<Exception, T> ifException)
{
if (_exception != null)
return ifException(_exception);
else
return ifValue(_value);
}
public override string ToString()
{
if (_exception != null)
return string.Format("Exception: {0}", _exception);
else
return string.Format("Value: {0}", _value);
}
}
public static class ValueOrException
{
public static ValueOrException<T> Value<T>(T value)
{
return ValueOrException<T>.Value(value);
}
public static ValueOrException<T> Exception<T>(Exception e)
{
return ValueOrException<T>.Exception(e);
}
public static IEnumerable<ValueOrException<TValue>> Catch<TValue>(this IEnumerable<TValue> source)
{
if (source == null)
throw new ArgumentNullException("source");
using (var e = source.GetEnumerator())
{
while (true)
{
ValueOrException<TValue> value;
try
{
if (!e.MoveNext())
yield break;
value = Value(e.Current);
}
catch (Exception ex)
{
value = Exception<TValue>(ex);
}
yield return value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment