CSharpFunctionalExtensions icon indicating copy to clipboard operation
CSharpFunctionalExtensions copied to clipboard

Func<T> to Result<T>

Open leandromoh opened this issue 6 years ago • 1 comments

Hi! I have a personal project with a class similar to Result<T> and I have the following method, which is used to wrap code on Result structure.

I am planning to submit a PR for this. What do you think?

Code

public static Result<T> ToResult<T>(this Func<T> func)
{
    try
    {
       return Result.Ok(func());
    }
    catch (Exception ex)
    {
       return Result.Fail<T>(ex.Message);
    }
}

Usage

public Result<TDTO> GetById(TKey key) 
{
    return Result.ToResult(() => ToDTO(Repository.GetById(key)));
}

leandromoh avatar Sep 12 '17 02:09 leandromoh

ToResult itself looks good but beware about its usage. I'd recommend not nesting one method into another the way you did (ToDTO(Repository.GetById(key))) as it makes it unclear which of the two methods is supposed to fail. Here's a better usage sample (assuming that it's the repository that fails here):

public Result<TDTO> GetById(TKey key) 
{
    return Result.ToResult(() => Repository.GetById(key))
        .OnSuccess(x => ToDto(x)); // OnSuccess == Bind
}

Also, I would only recommend doing that for code code you don't have control over, such as external libraries. In your own code base, just return Result from Repository.GetById

vkhorikov avatar Sep 12 '17 11:09 vkhorikov