C# functional extensions NuGet library

I’ve created a NuGet package out of the functional extensions I wrote about in this post series and in my Pluralsight course.

C# functional extensions NuGet library

Thanks to one of the listeners of my Functional C# course, I finally made a separate NuGet package which is based on the Result class I wrote about awhile ago.

The package contains the following classes:

  • Result

  • ResultExtensions

  • Maybe

  • MaybeExtensions

  • ValueObject

These classes allow you to compose multiple operations into a single chain:

public HttpResponseMessage Promote(long id)
{
    return _customerRepository.GetById(id)
        .ToResult("Customer with such Id is not found: " + id)
        .Ensure(customer => customer.CanBePromoted(), "Unable to promote")
        .OnSuccess(customer => customer.Promote())
        .OnSuccess(customer => _emailGateway.SendEmail(customer.PrimaryEmail, customer.Status))
        .OnBoth(result => result.IsSuccess ? Ok() : Error(result.Error));
}

That is basically an adaptation of the Railway programming approach for C#.

This coding style is quite useful but has a major challenge. That is, there are a lot of different variations of the OnSuccess, OnFailure, and OnBoth extension methods. They differ subtly for various use cases and it might become quite hard to figure out which one you need to introduce in your own code base to make the chain work.

The idea behind the NuGet package is to alleviate this burden and gather all overloads for OnSuccess, OnFailure, and OnBoth extension methods in a single place so that you don’t need to do this work yourself.

You can find the source code here and the package itself - here.

At the moment, there are not a lot of extension methods, but it’s a good point to start from. If you see a use case which is not supported by the existing overloads, leave a comment below describing your situation and I’ll add appropriate extensions to the library. Or send me a pull request if you prefer to add them yourself.

Subscribe


I don't post everything on my blog. Don't miss smaller tips and updates. Sign up to my mailing list below.

Comments


comments powered by Disqus