Table of Contents

Rascal

Rascal is a simple yet powerful result type implementation for C#, containing a variety of utilities and standard functions for working with result types and integrating them into the rest of C#.

Rascal is first and foremost an aggregate of the result types I personally find myself implementing in a majority of my own projects, and a competetor other result libraries second. As such, this library implements some things I think other result implementations are lacking, while omitting some features other libraries do implement.

Additionally, Rascal comes with a suite of analyzers and code fixes to help you write better and more reliable code using the library. The documentation for these analyzers can be found in the diagnostics documentation.


Installation

Run in a terminal in the root of your project:

dotnet add package Rascal --prerelease

Quick start

After installing the package, create a file called Usings.cs and add the following:

global using static Rascal.Prelude;

Prelude includes a variety of utility functions which you can now access from anywhere in your project.

Now, let's pretend you have an ASP.NET Core app with the following method in a service:

public Task<User?> GetUser(int userId)
{
    var user = db.Users.FirstOrDefaultAsync(user => user.Id == userId);

    return user;
}

... you can replace it with:

public Task<Result<User>> GetUser(int userId) => TryAsync(async () =>
{
    var user = await db.Users.FirstOrDefaultAsync(user => user.Id == userId);

    if (user is null) return new NotFoundError($"User with ID {userId} does not exist.");

    return user;
});

This code will handle catching any exceptions thrown by FirstOrDefaultAsync and will return a NotFoundError if the user isn't found. Now you can use this method as such:

app.MapGet("/users/{id}", async (int id, IUserService userService) =>
{
    var userResult = await userService.GetUser(id);

    return userResult.Match(
        user => Results.Ok(user),
        error => error switch
        {
            NotFoundError => Results.NotFound(),
            _ => Results.Problem(detail: error.Message, statusCode: 500)
        }
    );
});

More samples

A plethora of additional code samples are available in the samples section of the documentation.


Explore the API

Once you're ready to dive into the library, feel free to refer to the API documentation for an in-depth look into each of the methods provided by the library. You can of course also explore the API through intellisense in your IDE of choice.


Other great libraries

Some libraries Rascal takes inspiration from: