Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private class Result<T> {
- private readonly T? value;
- private readonly Exception? exception;
- public T Value {
- get {
- if (this.exception != null)
- throw this.exception; // maybe ExceptionDispatchInfo.Throw()?
- return this.value!;
- }
- }
- private Result(T? value, Exception? exception) {
- this.value = value;
- this.exception = exception;
- }
- public Result<V> Map<V>(Func<T, V> mapper) {
- if (this.exception != null)
- return Result<V>.FromException(this.exception);
- V result;
- try {
- result = mapper(this.value!);
- }
- catch (Exception e) {
- return Result<V>.FromException(e);
- }
- return Result<V>.FromValue(result);
- }
- public static Result<T> FromException(Exception exception) => new Result<T>(default, exception);
- public static Result<T> FromValue(T value) => new Result<T>(value, null);
- public static Result<T> Run(Func<T> factory) {
- T result;
- try {
- result = factory();
- }
- catch (Exception e) {
- return FromException(e);
- }
- return FromValue(result);
- }
- public static async Task<Result<T>> RunAsync(Func<Task<T>> factory) {
- T result;
- try {
- result = await factory();
- }
- catch (Exception e) {
- return FromException(e);
- }
- return FromValue(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment