Created
November 16, 2025 18:18
-
-
Save DimsFromDergachy/ced427453f90c289707f628657e72c2e to your computer and use it in GitHub Desktop.
awaiter using as a TResult monad
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
| using System.Runtime.CompilerServices; | |
| var user1 = await GetUserById(id: 12); | |
| var address1 = await GetUserAddress(user1); | |
| Console.Out.WriteLine(address1.ToUpper()); | |
| var user2 = await GetUserById(id: 13); | |
| var address2 = await GetUserAddress(user2); | |
| Console.Out.WriteLine(address2.ToUpper()); | |
| Result<int, string> GetUserById(int id) => id switch | |
| { | |
| 12 => Result<int, string>.Success(1234), | |
| _ => Result<int, string>.Failure("not found"), | |
| }; | |
| Result<string, string> GetUserAddress(int id) => id switch | |
| { | |
| 1234 => Result<string, string>.Success("Moscow"), | |
| _ => Result<string, string>.Failure("not found"), | |
| }; | |
| record Result<TValue, TError> | |
| { | |
| public TValue? Value { get; private set; } | |
| public TError? Error { get; private set; } | |
| public bool IsSuccess => Value != null; | |
| public static Result<TValue, TError> Success(TValue value) | |
| => new Result<TValue, TError>() { Value = value }; | |
| public static Result<TValue, TError> Failure(TError error) | |
| => new Result<TValue, TError>() { Error = error }; | |
| public ResultAwaiter<TValue, TError> GetAwaiter() | |
| => new ResultAwaiter<TValue, TError>(this); | |
| } | |
| class ResultAwaiter<TValue, TError> : INotifyCompletion | |
| { | |
| private readonly Result<TValue, TError> _result; | |
| public ResultAwaiter(Result<TValue, TError> result) => _result = result; | |
| public bool IsCompleted => true; | |
| public void OnCompleted(Action continuation) | |
| { | |
| if (_result.IsSuccess) | |
| continuation(); | |
| else | |
| throw new Exception(_result.Error!.ToString()); | |
| } | |
| public TValue GetResult() => _result.IsSuccess switch | |
| { | |
| true => _result.Value!, | |
| _ => throw new Exception(_result.Error!.ToString()), | |
| }; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output: