Skip to content

Instantly share code, notes, and snippets.

@jnm2
Created November 16, 2016 15:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnm2/8b49993b141650b27f7b80d23cceff2d to your computer and use it in GitHub Desktop.
Save jnm2/8b49993b141650b27f7b80d23cceff2d to your computer and use it in GitHub Desktop.
[DebuggerDisplay("{ToString(),nq}")]
public struct ResultOrException<T>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly T result;
public ResultOrException(T result)
{
this.result = result;
Exception = null;
}
public ResultOrException(Exception exception)
{
result = default(T);
Exception = exception;
}
/// <summary>
/// Compare this property to null to determine whether this represents a result or an exception.
/// </summary>
public Exception Exception { get; }
/// <summary>
/// If Exception is not null, reading this property throws it to provide a convenient shorthand. If you do not want to throw, compare Exception to null to determine whether this represents a result or an exception.
/// </summary>
public T Result
{
[DebuggerNonUserCode]
get
{
if (Exception != null) throw Exception;
return result;
}
}
public static implicit operator ResultOrException<T>(Exception exception) => new ResultOrException<T>(exception);
public static implicit operator ResultOrException<T>(T result) => new ResultOrException<T>(result);
public override string ToString() => Exception != null ? $"Exception: \"{Exception.Message}\"" : "Result: " + (Result?.ToString() ?? "(null)");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment