LightResults 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.
- πͺΆ Lightweight β Only contains what's necessary to implement the Result Pattern.
- βοΈ Extensible β Simple interfaces and base classes make it easy to adapt.
- 𧱠Immutable β Results and errors are immutable and cannot be changed after being created.
- 𧡠Thread-safe β The Error list and Metadata dictionary use Immutable classes for thread-safety.
- β¨ Modern β Built against the latest version of .NET using the most recent best practices.
- π§ͺ Native β Written, compiled, and tested against the latest versions of .NET.
- β€οΈ Compatible β Available for dozens of versions of .NET as a .NET Standard 2.0 library.
- πͺ Trimmable β Compatible with ahead-of-time compilation (AOT) as of .NET 7.0.
- π Performant β Heavily optimized and benchmarked to aim for the highest possible performance.
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
.
- The
Result
class represents a generic result indicating success or failure. - The
Result<TValue>
class represents a result with a value. - The
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.
if (result.Error.Message.Length > 0)
Console.WriteLine(result.Error.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();
}
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.Failt(notFoundError);
}
public TResult NotFound<TResult>()
{
var notFoundError = new NotFoundError();
return TResult.Fail(notFoundError);
}
}