CSharpFunctionalExtensions icon indicating copy to clipboard operation
CSharpFunctionalExtensions copied to clipboard

Question: Is there a method to do this?

Open SuperJMN opened this issue 4 years ago • 3 comments

I'd like to know if there's already a method that given a Result<T, E> result

When the result is success => returns it When the result is failure => applies a Func<E, T> that converts the E into a T

In short: it returns the success value, or if the result is a failure it gives you the chance to convert it into a successs (applying a func)

Some tests:

var result = Result.Success<int, string>(123);
var actual = result.Operation(e => 0);
actual.Should().Be(123);
var result = Result.Failure<int, string>("Errored");
var actual = result.Operation(e => 0);
actual.Should().Be(0);

BTW, it should also be present for Result<T>

Thanks in advance!

EDIT

I've created this implementation of this operator. I called it Handle

public static T Handle<T>(this Result<T> result, Func<string, T> convertToSuccess)
{
    var mapError = result.MapError(convertToSuccess);
    return mapError.Match(s => s, s => s);
}

public static T Handle<T, E>(this Result<T, E> result, Func<E, T> convertToSuccess)
{
    var mapError = result.MapError(convertToSuccess);
    return mapError.Match(s => s, s => s);
}

SuperJMN avatar Nov 07 '21 14:11 SuperJMN

I think you're looking for something like OnFailureCompensate.

hankovich avatar Nov 08 '21 10:11 hankovich

Sorry, I've edited the implementation above. It should return T, not Result<T>.

SuperJMN avatar Nov 08 '21 11:11 SuperJMN

Aha, I see. You probably need some kind of GetValueOrDefault. It's mentioned here (https://github.com/vkhorikov/CSharpFunctionalExtensions/issues/351), but is not yet implemented :)

But it's implemented for Maybe , so you can get a general idea.

hankovich avatar Nov 08 '21 11:11 hankovich