Skip to content

Instantly share code, notes, and snippets.

@chivandikwa
Last active October 15, 2019 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chivandikwa/da92642708665e59bc0cb6dc4acd92d5 to your computer and use it in GitHub Desktop.
Save chivandikwa/da92642708665e59bc0cb6dc4acd92d5 to your computer and use it in GitHub Desktop.
Result class for use across boundaries
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