API Reference
The complete public surface of QuickResult 2.5 — one namespace, QuickResult,
zero dependencies, targeting .NET 10 and .NET Standard 2.0. Descriptions are drawn from the package's
own XML documentation.
Result<T>
Represents the outcome of an operation that can either succeed with a value of type
T or fail with an IError.
| Member | Description |
|---|---|
IsSuccess | Whether the result represents success. |
IsFailure | Whether the result represents failure. |
Value | The success value. Throws InvalidOperationException if accessed on a failure — check IsSuccess or prefer Match/ValueOr. |
Error | The failure error. Throws InvalidOperationException if accessed on a success. |
Success(T value) | Creates a successful result containing value. |
Failure(IError error)Failure(string error) | Creates a failed result. The error message must be non-empty. |
Map<TOut>(Func<T, TOut>) | Transforms the success value; failures pass through unchanged. |
Bind<TOut>(Func<T, Result<TOut>>) | Chains a result-producing operation onto a success; failures pass through. |
MapFailure(Func<IError, IError>) | Transforms the error while preserving successes — ideal for adding context as failures bubble up. |
ValueOr(T fallback)ValueOr(Func<IError, T>) | Unwraps the value, or produces a fallback (optionally from the error). |
left | right | Or-operator: returns left when successful, otherwise right. A fallback strategy at the Result level. |
ToString() | Success(value) or Failure(error). |
C# union support
On .NET 10 and later, Result<T> is a C# union of T and
IError. With C# 15 (the .NET 11 SDK) you can match a result by type, and the
compiler checks that both cases are handled:
Result<int> result = ParsePositive(input);
string text = result switch
{
int value => $"Got {value}",
IError error => $"Failed: {error.Message}"
};
if (result is IError failure)
Console.WriteLine(failure.Message);
Custom error types can have their own arms:
string status = result switch
{
int value => "200",
NotFoundError => "404",
IError => "500"
};
A value or an error converts implicitly to a result, so methods can return either directly:
Result<int> ParsePositive(string text)
{
if (int.TryParse(text, out var number) && number > 0)
return number;
return new Error("Not a positive integer");
}
For the background — what C# union types are and how Result<T>
implements them — read C# union types, and how Result<T> became one.
Notes
- Matching a value-type result (such as
Result<int>) does not box. - Projects targeting .NET 10 need
<LangVersion>15</LangVersion>(orlatest) and the .NET 11 SDK. Projects targeting .NET 11 need nothing extra. - Union support is in the .NET 10+ build only. Projects that resolve the .NET Standard 2.0 build (.NET Framework, .NET 8, .NET 9) keep the rest of the API unchanged.
- A successful result holding
nullmatches neither arm; add anullarm whenTis nullable. For the same reasonresult is nullis true for such a result, so useIsSuccessto tell the two apart. - A type pattern cannot tell success from failure when
ToverlapsIError(TisIError,object, or an error type):IError ealso matches a successful value that is an error, and aTarm also matches a failure whose error is aT. UseIsSuccessorMatchfor those. - Implicit conversion follows the same overlap: an error assigned to a
Result<object>becomes a failure, and assigning one to aResult<IError>does not compile.Success(...)andFailure(...)are always unambiguous. IsSuccess,Value,Error,Matchand property patterns such asresult is { IsSuccess: true }work as before.- Under C# 15, patterns on a result test what it holds, so
result is Result<int>no longer compiles whenresultis already typedResult<int>. Matching fromobject(obj is Result<int> r) is unaffected. Result<T>.IUnionMembersis compiler infrastructure that describes the union to the compiler; it is not intended to be used directly.
Result — factory methods
Convenience factories that let type inference do the work at the call site.
| Method | Description |
|---|---|
Success<T>(T value) | Successful Result<T>; T is inferred. |
Success() | Successful Result<Unit> for operations with no payload. |
Failure<T>(IError | string) | Failed Result<T>. |
FromNullable<T>(T? value, string error) | Success when the value is non-null; otherwise a failure with error. Overloads cover both reference and value types. |
Try<T>(Func<T>)Try(Action) | Runs the delegate; a thrown exception becomes a failure carrying the exception message. |
TryAsync<T>(Func<Task<T>>)TryAsync(Func<Task>) | Async version of Try. |
From<T>(Func<T>) | Creates a deferred ResultPipeline<T> source from a synchronous function. |
FromAsync<T>(Func<Task<T>>) | Creates a deferred pipeline source from an async function. An overload accepts ConfiguredTaskAwaitable<T> for ConfigureAwait(false) callers. |
IError & Error
IError is the contract every failure carries — a single
string Message property. Implement it to create structured, domain-specific
error types (HTTP errors, validation errors) and recover them with ordinary C# pattern
matching (is, as, switch).
public sealed record ValidationError(string Field, string Message) : IError;
var result = Result.Failure<Order>(
new ValidationError("Email", "Email address is required"));
var response = result.Match(
onSuccess: order => Ok(order),
onFailure: e => e switch
{
ValidationError v => UnprocessableEntity($"{v.Field}: {v.Message}"),
_ => Problem(e.Message),
});
Error is the built-in default implementation wrapping a string message, with
implicit conversions to and from string — which is why plain strings work
anywhere an IError is expected. Empty or whitespace messages are rejected
with ArgumentException.
Unit
A void-like value for operations that succeed without producing data —
Result<Unit> is QuickResult's answer to "a Result with no payload."
Its single value is Unit.Value; Result.Success() and
Result.Try(Action) produce it for you.
LINQ extensions
ResultLinqExtensions provides Select and SelectMany
over Result<T>, which is what makes from/select
query syntax work. ResultAsyncLinqExtensions adds the overloads over
Task<Result<T>> — covering async→sync, sync→async, and async→async
binds — so one query can mix both worlds:
var query =
from a in Result.Success(4) // Result<int> (sync)
from b in GetAsync(6) // Task<Result<int>> (async)
from c in Result.Success(2) // back to sync — no adapters
select a + b + c;
var result = await query; // Success(12)
| Method | Description |
|---|---|
Select | Projects a success value (backs select). Sync and async source overloads. |
SelectMany | Binds then projects (backs multiple from clauses). Four overloads cover every sync/async combination of source and binder. |
Transpose<T>() | Turns Result<Task<T>> inside-out into Task<Result<T>>, capturing exceptions from the inner task as failures. |
Match extensions
Match projects a Result into a single value by invoking exactly one of two
delegates. MatchAsync provides seven additional overloads spanning every
combination of sync/async source, success handler, and failure handler — so you never
write adapter lambdas:
| Method | Description |
|---|---|
Match(onSuccess, onFailure) | Synchronous branch — both delegates return TResult. |
MatchAsync(...) | Overloads for Result<T> and Task<Result<T>> sources with any mix of sync and async handlers; all return Task<TResult>. |
Guards — ResultGuardExtensions
Boolean guards turn checks into failures without leaving the flow. They are intentionally
restricted to Result<bool> to keep the API explicit.
| Method | Description |
|---|---|
FailIfTrue(string error) | Fails with error when the successful boolean is true. Existing failures propagate unchanged. Sync and Task-wrapped overloads. |
FailIfFalse(string error) | Fails when the successful boolean is false. Same propagation rules. |
Pipelines — ResultPipeline<T>
A ResultPipeline<T> is a deferred source: nothing executes until
the pipeline is materialized. This lets you declare how the value is fetched, how exceptions
are handled, and how nulls are treated — as one readable chain:
var value = await Result
.FromAsync(() => service.GetValueAsync(ct)) // deferred — nothing runs yet
.Try() // run; exceptions → failures
.WhenNull("Value was null"); // null → failure, T? → T
| Method | Description |
|---|---|
Result.From / Result.FromAsync | Create the deferred source. |
.Try() | Executes the pipeline; any thrown exception becomes a failure. |
.WhenNull(string error) | Converts a successful-but-null value into a named failure and narrows the type from T? to T. Reference and nullable-value-type overloads. |
Technical implementation
Two design decisions do most of the work in QuickResult:
Query syntax is just method resolution
The C# compiler lowers from a in x from b in f(a) select g(a, b) into calls to
SelectMany(x, f, g) — it doesn't care what x is, only that a
suitable SelectMany exists. QuickResult supplies those methods for
Result<T> and Task<Result<T>>, in every
source/binder combination. The moment any step in a query is async, overload resolution
selects a Task-returning SelectMany, the rest of the query chains
on Task<Result<T>>, and you await once at the end. Mixed sync/async
composition falls out of the type system — no schedulers, no state machines of its own,
no blocking.
Failures short-circuit by construction
Every combinator (Map, Bind, SelectMany, guards,
WhenNull) checks IsFailure first and propagates the existing error
without invoking your delegate. There is no hidden control flow: a failure simply flows
through every remaining step untouched, which is why a ten-step query with a failure at
step two costs eight cheap pass-throughs, not eight try/catch frames.
Package facts
- Single assembly, zero runtime dependencies.
- Targets
net10.0andnetstandard2.0, so it runs on .NET 10+ and, through .NET Standard 2.0, on .NET Framework 4.7.2+ and older .NET versions. - Nullable reference types are honored throughout —
WhenNullandFromNullablegenuinely narrowT?toT. - Invalid states are unrepresentable at the edges: empty error messages and null errors are rejected with argument exceptions at construction time.
- MIT licensed; symbols (
.snupkg) published for debugging.