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, and .NET 8.0.
This library has no dependencies.
LightResults consists of only three classes , , and .
ResultResult<TValue>ErrorResult class represents a generic result indicating success or failure.Result<TValue> class represents a result with a value.Error class represents an error with a message and associated metadata.Successful results can be created using the Ok method.
var successResult = Result.Ok();
var successResultWithValue = Result.Ok(349.4);
Failed results can be created using the Fail method.
var failedResult = Result.Fail();
var failedResultWithMessage = Result.Fail("Operation failed!");
var failedResultWithMessageAndMetadata = Result.Fail("Operation failed!", ("Exception", ex));
There are two properties for results, IsSuccess and IsFailed. Both are mutually exclusive.
if (result.IsSuccess)
{
// The result is successful therefore IsFailed will be false.
}
if (result.IsFailed)
{
// The result is failed therefore IsSuccess will be false.
var firstError = result.Errors.First();
if (firstError.Message.Length > 0)
Console.WriteLine(firstError.Message);
else
Console.WriteLine("An unknown error occured!");
}
The value from a successful result can be retrieved through the Value property.
if (result.IsSuccess)
{
var value = result.Value;
}
Errors can be created with or without a message.
var errorWithoutMessage = new Error();
var errorWithMessage = new Error("Something went wrong!");
With metadata.
var errorWithMetadataTuple = new Error(("Key", "Value"));
var metadata = new Dictionary<string, object> { { "Key", "Value" } };
var errorWithMetadataDictionary = new Error(metadata);
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.Fail(notFoundError);
Then the result can be checked against that error type.
if (result.IsFailed && result.HasError<NotFound>())
{
// Looks like the resource was not found, we better do something about that!
}
This can be especially useful when combined with metadata to handle exceptions.
public sealed class UnhandledExceptionError : Error
{
public UnhandledExceptionError(Exception ex)
: base("An unhandled exception occured.", ("Exception", ex))
{
}
}
Which allows us to continue using try-catch blocks in our code but return from them with a result instead of throwing an exception.
public Result DoSomeWork()
{
try
{
// We must not throw an exception in this method!
}
catch(Exception ex)
{
var unhandledExceptionError = new UnhandledExceptionError(ex);
return Result.Fail(unhandledExceptionError);
}
return Result.Ok();
}
We can further simplify creating errors by creating an error factory.
public static AppError
{
public Result NotFound()
{
var notFoundError = new NotFoundError();
return Result.Fail(notFoundError);
}
public Result UnhandledException(Exception ex)
{
var unhandledExceptionError = new UnhandledExceptionError(ex)
return Result.Fail(unhandledExceptionError);
}
}
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.Ok();
}
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.Failt(notFoundError);
}
public TResult NotFound<TResult>()
{
var notFoundError = new NotFoundError();
return TResult.Fail(notFoundError);
}
}