Skip to content

Commit 0309d6d

Browse files
Adds Unwrap method for IResult<TValue>
1 parent 84d77f8 commit 0309d6d

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/FluentResults/Extensions/ResultExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ public static async Task<Result<TValue>> ToResult<TValue>(this ValueTask<Result>
336336
#endregion
337337

338338

339-
#region Extensions for Task<IResultBase>, ValueTask<IResultBase>, Task<IResult<T>>, and ValueTask<IResult<T>>
339+
#region Extensions for Task<IResultBase>, ValueTask<IResultBase>, Task<IResult<T>>, and ValueTask<IResult<T>>
340340

341341
#if false
342342
public static async Task<IResultBase> MapErrors(this Task<IResultBase> resultTask, Func<IError, IError> errorMapper)

src/FluentResults/Extensions/ResultTValueExtensions.cs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Linq;
33
using System.Collections.Generic;
44
using System.Threading.Tasks;
@@ -67,6 +67,39 @@ public static Result<TNewValue> Map<TValue, TNewValue>(this IResult<TValue> resu
6767
.WithReasons(result.Reasons);
6868
}
6969

70+
/// <summary>
71+
/// Unwraps the value of the result.
72+
/// </summary>
73+
/// <remarks>
74+
/// if <paramref name="result"/> is successful, it returns its value, otherwise
75+
/// <paramref name="onError"/> is called with the erroneous result.
76+
/// </remarks>
77+
/// <typeparam name="TValue">
78+
/// The underlying type of the result.
79+
/// </typeparam>
80+
/// <param name="result">
81+
/// The result, that is to be unwrapped.
82+
/// </param>
83+
/// <param name="onError">
84+
/// Mapper for the result in case of error.
85+
/// (Could also throw an exception instead.)
86+
/// </param>
87+
/// <returns>
88+
/// Return <c>result.Value</c> if result is successful
89+
/// and the result of the call to <paramref name="onError"/>
90+
/// if the result is not successful.
91+
/// </returns>
92+
static public TValue Unwrap<TValue>(this IResult<TValue> result, Func<IResult<TValue>, TValue> onError)
93+
{
94+
if(result?.IsSuccess is true)
95+
{
96+
return result.Value;
97+
}
98+
else
99+
{
100+
return onError(result);
101+
}
102+
}
70103

71104
#region Variants of Bind(), that return result with value
72105

0 commit comments

Comments
 (0)