bobmarley12345

Railway?

Sep 19th, 2025 (edited)
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. private class Result<T> {
  2.     private readonly T? value;
  3.     private readonly Exception? exception;
  4.  
  5.     public T Value {
  6.         get {
  7.             if (this.exception != null)
  8.                 throw this.exception; // maybe ExceptionDispatchInfo.Throw()?
  9.             return this.value!;
  10.         }
  11.     }
  12.  
  13.     private Result(T? value, Exception? exception) {
  14.         this.value = value;
  15.         this.exception = exception;
  16.     }
  17.  
  18.     public Result<V> Map<V>(Func<T, V> mapper) {
  19.         if (this.exception != null)
  20.             return Result<V>.FromException(this.exception);
  21.         V result;
  22.         try {
  23.             result = mapper(this.value!);
  24.         }
  25.         catch (Exception e) {
  26.             return Result<V>.FromException(e);
  27.         }
  28.         return Result<V>.FromValue(result);
  29.     }
  30.  
  31.     public static Result<T> FromException(Exception exception) => new Result<T>(default, exception);
  32.  
  33.     public static Result<T> FromValue(T value) => new Result<T>(value, null);
  34.  
  35.     public static Result<T> Run(Func<T> factory) {
  36.         T result;
  37.         try {
  38.             result = factory();
  39.         }
  40.         catch (Exception e) {
  41.             return FromException(e);
  42.         }
  43.         return FromValue(result);
  44.     }
  45.  
  46.     public static async Task<Result<T>> RunAsync(Func<Task<T>> factory) {
  47.         T result;
  48.         try {
  49.             result = await factory();
  50.         }
  51.         catch (Exception e) {
  52.             return FromException(e);
  53.         }
  54.         return FromValue(result);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment