Last active
July 5, 2022 09:29
-
-
Save iBener/bf744924062a325817fd9beb206ed06c to your computer and use it in GitHub Desktop.
Result struct for service returns
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
public readonly struct Result<T> | |
{ | |
public Result(T value) | |
{ | |
IsSuccess = true; | |
Value = value; | |
Exception = null; | |
} | |
public Result(Exception e) | |
{ | |
IsSuccess = false; | |
Exception = e; | |
Value = default; | |
} | |
[Pure] | |
public T? Value { get; init; } | |
[Pure] | |
public Exception? Exception { get; init; } | |
[Pure] | |
public bool IsSuccess { get; init; } | |
[Pure] | |
public T? IfFail(T? defaultValue) | |
{ | |
if (!IsSuccess) | |
{ | |
return defaultValue; | |
} | |
return Value; | |
} | |
[Pure] | |
public static implicit operator Result<T>(T value) => new(value); | |
[Pure] | |
public static implicit operator Result<T>(Exception exception) => new(exception); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment