
Maple.Result
The Result pattern for .NET: an operation returns a Result or a Result<T>, which is either successful (with or without a value) or failed (with an Error that follows RFC 9457: Problem Details for HTTP APIs).
Check also:
[!IMPORTANT]
Version 3.0 is a major release with breaking changes, and this README describes it. Result, Result<T> and Error are immutable (with a new ErrorBuilder), the namespace is Maple.Results, the transforming IfSuccess / IfError are Then / Else, and the types can no longer be read from JSON without the converter packages. Read the migration guide from 2.x to 3.0 before you upgrade, and upgrade the related packages together with Maple.Result.
Contents
Why this library?
The Result pattern returns the outcome of an operation—either successful or failed—in a structured and precise way:
- No guessing what the
null means!
- Clear way of indicating whether the operation is successful!
- No need for misusing exceptions for not exceptional cases or controlling the flow!
There are many implementations of the Result pattern in C#. This one adds a few things that are missing in others:
- consistent error categorization (e.g.,
Validation, NotFound, Conflict), with a default HTTP status code for each category,
- precise error description: a type URI, a title, a detail, an instance URI, error details (e.g., one per invalid field) and machine-readable metadata,
- following standards (RFC 9457),
- support for localization (a message template and its parameters next to each message),
- Native AOT and trimming compatibility (checked by the trim and AOT analyzers in every build), and no dependencies.
See The Result pattern for its benefits, a comparison with exceptions and when to use which.
Installation
Add the Maple.Result package to your project using the Package Manager in your IDE or the dotnet tool in the console:
dotnet add package Maple.Result
The types are in the Maple.Results namespace, and the extension methods in Maple.Results.Extensions:
using Maple.Results;
using Maple.Results.Extensions; // extension methods: Then, Else, IfSuccess, Match, Switch, LINQ, …
Quick start
Return a Result<T> (or a Result, when there is no value) instead of throwing an exception for an expected failure. A value and an Error convert to it implicitly:
public async Task<Result<Contact>> GetContactAsync(Guid id)
{
if (id == Guid.Empty)
{
return Error.Validation(
ErrorUri.Tag("tag:exampleapp.com,2026:errors:contact:id:invalid"),
"Invalid contact ID.",
"The contact ID must not be empty.");
}
var contact = await _contactRepository.GetByIdAsync(id);
if (contact is null)
{
return Error.NotFound(
ErrorUri.Tag("tag:exampleapp.com,2026:errors:contact:notfound"),
"The contact has not been found.");
}
return contact;
}
Read the value, or return the error early:
var contactResult = await GetContactAsync(id);
if (!contactResult.TryGetValue(out var contact, out var error))
{
return error;
}
Handle both cases:
string greeting = contactResult.Match(
contact => $"Hello, {contact.Name}!",
error => error.Title);
Or chain the next steps, which run only on success:
Result sendResult = await GetContactAsync(id)
.ThenAsync(contact => _emailService.SendWelcomeAsync(contact)) // returns a Task<Result>
.IfErrorAsync(error => _logger.LogWarning("{Title}", error.Title));
Features
- Results —
Result and Result<T>, the implicit conversions, TryGetValue and TryGetError, and nullable values.
- Errors — eleven categories (with their default HTTP status codes), type and instance URIs, error details for validation errors (with JSON Pointers), metadata, the ErrorBuilder and localization.
- Chaining operations —
Then, Else, IfSuccess, IfError, Match, Switch, their asynchronous versions for Task and ValueTask, and the LINQ query syntax.
- Turning exceptions into results —
Result.Try() and Result.TryAsync() with a mapper from the exception to the Error.
- Analyzer — six rules in the package, with nothing to install, report the calls that compile but lose a task or a failure: e.g., a task that nobody awaits in
Then(), or a statement that discards a Result. Most of them have a code fix.
- Problem details format — how an
Error is written as an RFC 9457 problem details object and read back by the related packages.
- UI applications —
continueOnCapturedContext and a global default for WPF, Windows Forms, .NET MAUI and Blazor Server.
Related packages
The core package (Maple.Result) has no dependencies. These packages add the mapping to and from HTTP responses, resilience and JSON serialization:
| Package |
Purpose |
Status |
| Maple.Result.Extensions.AspNetCore |
Maps a Result to an ASP.NET Core HTTP response (ActionResult, problem details). |
Published (0.15.0, for Maple.Result 2.x); a version for 3.0 is released with it |
| Maple.Result.Extensions.MinimalApi |
Maps a Result to a .NET Minimal API result (IResult, problem details). |
Published (0.4.0, for Maple.Result 2.x); a version for 3.0 is released with it |
| Maple.Result.Extensions.Functions.Worker |
Maps a Result to an Azure Functions (isolated worker model) HTTP response (HttpResponseData). |
Published (0.2.0, for Maple.Result 2.x); a version for 3.0 is released with it |
| Maple.Result.Extensions.Functions.Worker.AspNetCore |
Maps a Result to an ActionResult in Azure Functions (isolated worker model) with the ASP.NET Core integration. |
Published (0.15.0, for Maple.Result 2.x); a version for 3.0 is released with it |
| Maple.Result.Extensions.HttpClient |
Maps an HttpClient response (HttpResponseMessage, problem details) to a Result. |
Published (0.12.0, for Maple.Result 2.x); a version for 3.0 is released with it |
| Maple.Result.Extensions.Resilience |
The retry-after metadata of an Error (e.g., for LimitExceeded) and helpers for the retry pipeline of an application (no dependency on Polly). |
Coming soon (not on NuGet yet) |
| Maple.Result.Serialization.SystemTextJson |
System.Text.Json converters that write and read Result, Result<T> and Error. |
Coming soon (not on NuGet yet) |
| Maple.Result.Serialization.NewtonsoftJson |
Newtonsoft.Json (Json.NET) converters that write and read Result, Result<T> and Error. |
Coming soon (not on NuGet yet) |
[!WARNING]
The published versions above are built for Maple.Result 2.x: do not mix them with Maple.Result 3.0 (e.g., the current Maple.Result.Extensions.HttpClient fails at runtime with 3.0). Upgrade all packages together, to the versions built for 3.0 (see Extension packages in the migration guide).
The problem details that these packages write and read follow one format, described in Problem details format.
Upgrading to 3.0
Version 3.0 has breaking changes. The main ones:
- the namespace is
Maple.Results (it was Maple.Result),
Result, Result<T> and Error are immutable: they have no public constructors or setters, with { … } no longer changes an error, and AddDetail() is replaced by WithErrorDetail() and the new ErrorBuilder,
- the transforming
IfSuccess() and IfError() are Then() and Else(), and the analyzer of the package reports most of the calls that changed meaning,
IsSuccess is a property, IsError is new, and Result<T>.Value throws on a failed result,
IResult is renamed to IOperationResult,
- the types can no longer be read from JSON without the converter packages,
- exhaustive
switch statements over ErrorCategory must handle the new LimitExceeded category.
The migration guide from 2.x to 3.0 has a checklist, before/after examples of every breaking change, the new features and a search-and-replace reference.
FAQ
When to use a Result and when an exception?
Use a Result for expected failures that you handle in the normal program flow or return in an API (e.g., validation, a missing resource, authorization), and exceptions for cases that require someone’s attention (e.g., a bug, an unavailable database, an expired API key). See When to use a Result and when an exception?
Why does Unauthenticated correspond to the 401 (Unauthorized) HTTP status code?
By the HTTP reference from Mozilla [link]:
Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.
The HTTP 401 Unauthorized client error response status code indicates that a request was not successful because it lacks valid authentication credentials for the requested resource.
A 401 Unauthorized is similar to the 403 Forbidden response, except that a 403 is returned when a request contains valid credentials, but the client does not have permissions to perform a certain action.
The 403 (Forbidden) status code corresponds to PermissionDenied: the identity is known, but it does not have the permission. The library does not use the name "Unauthorized", which means the other case in HTTP.
Why are methods like Bind(), Map() and Tap() not available?
This library minimizes the amount of extension methods:
Bind() and Map() are both Then(): a function that returns a value maps it (e.g., Then<T, TNext>(Result<T>, Func<T, TNext>)), and a function that returns a Result<TNext> binds it (e.g., Then<T, TNext>(Result<T>, Func<T, Result<TNext>>)),
Tap() is IfSuccess(), and TapError() is IfError(),
Recover() is Else() (e.g., Else<TResult>(TResult, Func<Error, TResult>)),
Fold() is Match(): two functions that return one type (e.g., Match<T, TOut>(Result<T>, Func<T, TOut>, Func<Error, TOut>)); Switch() runs two actions instead.
Documentation
Guides
- Results — returning and reading a
Result and a Result<T>
- Errors — categories, properties, URIs, error details, metadata,
ErrorBuilder and localization
- Chaining operations — extension methods, asynchronous operations, the query syntax and
Result.Try()
- Analyzer — the rules MR0001 to MR0006, their code fixes and their configuration
- The Result pattern — benefits, a comparison with exceptions, and articles
- Problem details format — how an
Error is written as an RFC 9457 problem details object and read back
- Migration guide from 2.x to 3.0
Reference
See also
Give it a star ⭐
Do you like it? Show your support by giving this project a star!
Contributing
Questions, ideas and contributions are welcome:
License
Maple.Result is licensed under the MIT License.