Skip to content

Commit

Permalink
feat(Result): Result.From()
Browse files Browse the repository at this point in the history
  • Loading branch information
MrBogomips committed Dec 13, 2024
1 parent 0c698b7 commit 7f842c4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Monads/Result/Result.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ public static async Task<Result<Unit>> Ensure(Func<Task<bool>> predicate, Func<E
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Task<Result<TValue>> Bind<TValue>(Func<Task<Result<TValue>>> result) => result();

/// <summary>
/// Initializes a new instance of the <see cref="Result{TValue}"/> with the value.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Result<T> From<T>(T value)
{
if (value is Error error) return Result.Failure<T>(error);
return Result.Success(value);
}

/// <summary>
/// Wraps the execution of the given <paramref name="action"/> in a <see cref="Result{TValue}"/>
/// catching any thrown exception and returning it as an <see cref="RuntimeError"/> .
Expand Down
14 changes: 14 additions & 0 deletions test/Monads.UnitTests/ResultTests/ResultCreationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,18 @@ public async Task Create_via_Result_from_successful_result_async()
result1.IsFailure.Should().Be(result2.IsFailure);
result1.GetValueOrThrow().Should().Be(result2.GetValueOrThrow());
}

[Fact]
public void Create_successfulResult_via_From()
{
var result = Result.From("value");
result.IsSuccess.Should().BeTrue();
}

[Fact]
public void Create_failedResult_via_From()
{
var result = Result.From(new LogicError("error"));
result.IsFailure.Should().BeTrue();
}
}

0 comments on commit 7f842c4

Please sign in to comment.