An extremely light and modern Result Pattern library.
$ dotnet add package LightResultsLightResults is an extremely light and modern .NET library that provides a simple and flexible implementation of the Result Pattern. The Result Pattern is a way of representing the outcome of an operation, whether it's successful or has encountered an error, in a more explicit and structured manner. This project is heavily inspired by Michael Altmann's excellent work with FluentResults.
This library targets .NET Standard 2.0, .NET 6.0, .NET 7.0, .NET 8.0, and .NET 9.0.
This library has no dependencies.
Several extensions are available to simplify implementation that use LightResults.
Make sure to read the docs for the full API.
LightResults consists of only three classes Result, Result<TValue>, and Error.
Result class represents a generic result indicating success or failure.Result<TValue> class represents a success or failure result with a value.Error class represents an error with a message and optional associated metadata.Successful results can be created using the Success method.
var successResult = Result.Success();
var successResultWithValue = Result.Success(349.4);Failed results can be created using the Failure method.
var failureResult = Result.Failure();
var failureResultWithMessage = Result.Failure("Operation failure!");
var failureResultWithMessageAndMetadata = Result.Failure("Operation failure!", ("UserId", userId));
var failureResultWithMessageAndException = Result.Failure("Operation failure!", ex);There are two methods used to check a result, IsSuccess() and IsFailed(). Both of which have several overloads to obtain the
value and error.
if (result.IsSuccess())
{
// The result is successful.
}
if (result.IsFailure(out var error))
{
// The result is failure.
if (error.Message.Length > 0)
Console.WriteLine(error.Message);
else
Console.WriteLine("An unknown error occured!");
}The value from a successful result can be retrieved through the out parameter of the Success() method.
if (result.IsSuccess(out var value))
{
Console.WriteLine($"Value is {value}");
}Errors can be created with or without a message.
var errorWithoutMessage = new Error();
var errorWithMessage = new Error("Something went wrong!");Or with a message and metadata.
var errorWithMetadataTuple = new Error("Something went wrong!", ("Key", "Value"));
var metadata = new Dictionary<string, object> { { "Key", "Value" } };
var errorWithMetadataDictionary = new Error("Something went wrong!", metadata);The best way to represent specific errors is to make custom error classes that inherit from Error
and define the error message as a base constructor parameter.
public sealed class NotFoundError : Error
{
public NotFoundError()
: base("The resource cannot be found.")
{
}
}
var notFoundError = new NotFoundError();
var notFoundResult = Result.Failure(notFoundError);Then the result can be checked against that error type.
if (result.IsFailure(out var error) && error is NotFoundError)
{
// Looks like the resource was not found, we better do something about that!
}Or checked to see if there are any errors of that type.
if (result.IsFailure() && result.HasError<NotFoundError>())
{
// At least one of the errors was a NotFoundError.
}This can be especially useful when combined with metadata that is related to a specific type of error.
public sealed class HttpError : Error
{
public HttpError(HttpStatusCode statusCode)
: base("An HTTP error occured.", ("StatusCode", statusCode))
{
}
}We can further simplify creating errors by creating an error factory.
public static AppError
{
public Result NotFound()
{
var notFoundError = new NotFoundError();
return Result.Failure(notFoundError);
}
public Result HttpError(HttpStatusCode statusCode)
{
var httpError = new HttpError(statusCode)
return Result.Failure(httpError);
}
}Which clearly and explicitly describes the results.
public Result GetPerson(int id)
{
var person = _database.GetPerson(id);
if (person is null)
return AppError.NotFound();
return Result.Success();
}Specific overloads have been added to Failure() and Failure<TValue>() to simplify using try-catch blocks and return from them with a result instead of
throwing.
public Result DoSomeWork()
{
try
{
// We must not throw an exception in this method!
}
catch(Exception ex)
{
return Result.Failure(ex);
}
return Result.Success();
}Note: Applies to .NET 7.0 (C# 11.0) or higher only!
Thanks to the static abstract members in interfaces introduced in .NET 7.0 (C# 11.0), it is possible to use generics to obtain access to the methods of the generic variant of the result. As such the error factory can be enhanced to take advantage of that.
public static AppError
{
public Result NotFound()
{
var notFoundError = new NotFoundError();
return Result.Failure(notFoundError);
}
public TResult NotFound<TResult>()
{
var notFoundError = new NotFoundError();
return TResult.Failure(notFoundError);
}
}The API for LightResults was completely redesigned for v9.0 to improve performance and remove any potential pits of failure caused by the prior version's use of properties that could result in exceptions being thrown when values were accessed without checking the state of the result. Thus, there are several breaking changes, detailed below, that developers must be aware of when upgrading from v8.0 to v9.0.
Result.Ok() has been renamed to Result.Success().Result.Fail() has been renamed to Result.Failure().Result<TValue>.Ok() has been renamed and moved to Result.Success<TValue>().Result<TValue>.Fail() has been renamed to Result.Failure<TValue>().Value and Error properties have been removed.
result.Value has been replaced by result.IsSuccess(out var value).result.Error has been replaced by result.IsError(out var error).Error type have been removed or have changed.
Error((string Key, object Value) metadata) has been removed.Error(IDictionary<string, object> metadata) has been removed.Error(string message, IDictionary<string, object> metadata) has been changed to
Error(string message, IReadOnlyDictionary<string, object> metadata).The following steps in the following order will reduce the amount of manual work required to migrate and refactor code to use the new API.
Result.Ok( with Result.Success(.Result.Fail( with Result.Failure(.Result(<[^>]+>)\.Ok\( with Result.Success$1(.Result(<[^>]+>)\.Fail\( with Result.Failure$1(..IsSuccess with IsSuccess(out var value)..IsFailed with IsFailure(out var error).result.Value and refactor them to the use the value exposed by the IsSuccess() method.result.Error and refactor them to the use the error exposed by the IsFailure() method.KeyValuePair<string, object> metadata.
Result.Failure(string errorMessage, KeyValuePair<string, object> metadata) has been added.Result.Failure<TValue>(string errorMessage, KeyValuePair<string, object> metadata) has been added.Result.Failure(Exception ex) has been added.Result.Failure(string errorMessage, Exception ex) has been added.Result.Failure<TValue>(Exception ex) has been added.Result.Failure<TValue>(string errorMessage, Exception ex) has been added.result.IsSuccess(out TValue value) has been added.result.IsFailure(out IError error, out TValue value) has been added.result.IsFailure(out IError error) has been added.result.IsSuccess(out TValue value, out IError error) has been added.result.HasError<TError>(out IError error) has been added.Error.
Message { get; } has changed to Message { get; init; }.Metadata { get; } has changed to Metadata { get; init; }.