Created
November 16, 2016 15:21
-
-
Save jnm2/8b49993b141650b27f7b80d23cceff2d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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