Last active
October 15, 2019 10:22
-
-
Save chivandikwa/da92642708665e59bc0cb6dc4acd92d5 to your computer and use it in GitHub Desktop.
Result class for use across boundaries
This file contains hidden or 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
public enum ResultState : byte | |
{ | |
Faulted, | |
Success | |
} | |
public struct Result<T> | |
{ | |
internal readonly ResultState State; | |
private readonly T _content; | |
private bool _successChecked; | |
internal Exception Exception { get; } | |
public T Content | |
{ | |
get | |
{ | |
if (!_successChecked) | |
throw new InvalidOperationException("Success must be checked before accessing Content"); | |
if (_content == null && IsFaulted) | |
throw new InvalidOperationException("Accessing Content of a failed result is not permitted"); | |
return _content; | |
} | |
} | |
public Result(T content) | |
{ | |
State = ResultState.Success; | |
Exception = null; | |
_content = content; | |
_successChecked = false; | |
} | |
public Result(Exception exception) | |
{ | |
State = ResultState.Faulted; | |
Exception = exception; | |
_content = default; | |
_successChecked = false; | |
} | |
public static implicit operator Result<T>(T value) => | |
new Result<T>(value); | |
public static implicit operator Result<T>(Exception exception) => | |
new Result<T>(exception); | |
public bool IsFaulted | |
{ | |
get | |
{ | |
_successChecked = true; | |
return State == ResultState.Faulted; | |
} | |
} | |
public bool IsSuccess | |
{ | |
get | |
{ | |
_successChecked = true; | |
return State == ResultState.Success; | |
} | |
} | |
public override string ToString() => | |
IsFaulted | |
? Exception?.ToString() ?? "(IsFaulted)" | |
: Content?.ToString() ?? "(null)"; | |
public static Result<T> Successful(T contents) | |
=> new Result<T>(content: contents); | |
public static Result<T> Failed(Exception exception) | |
=> new Result<T>(exception); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment