vkhorikov/CSharpFunctionalExtensions

Add type Result as predicate for .Ensure()

DerStimmler opened this issue · 4 comments

At the moment the .Ensure() method signature looks like this:
public static Result Ensure(this Result result, Func<bool> predicate, string errorMessage)

It takes a boolean predicate (Func<bool>) and an error message string.
It returns a new failure result with the provided error message if the predicate is false. Otherwise, it returns the starting result.

The method should also be able to take a predicate of type Result (Func<Result>). If the predicate is a failure result it returns a new failure result with the error message from the predicate, otherwise it returns the starting result.

The method signature would be:
public static Result Ensure(this Result result, Func<Result> predicate)

Please take a look at Bind, I think this's exactly what you are looking for.

Not exactly.

When I use .Ensure()

return Result.Success("ResultMessage")
              .Ensure(_ => true, "ErrorMessage")
              .Finally(result => result.IsSuccess ? result.Value : result.Error));

it returns "ResultMessage" as expected.

But when I do the same thing with .Bind()

return Result.Success("ResultMessage")
            .Bind(_ => Result.Success("SuccessMessage"))
            .Finally(result => result.IsSuccess ? result.Value : result.Error));

it returns "SuccessMessage" although I want the original result "ResultMessage".

Looks like a good addition. Feel free to submit a PR.

Cool, I'll give it a shot.