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.

MemberDescription
IsSuccessWhether the result represents success.
IsFailureWhether the result represents failure.
ValueThe success value. Throws InvalidOperationException if accessed on a failure — check IsSuccess or prefer Match/ValueOr.
ErrorThe 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 | rightOr-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> (or latest) 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 null matches neither arm; add a null arm when T is nullable. For the same reason result is null is true for such a result, so use IsSuccess to tell the two apart.
  • A type pattern cannot tell success from failure when T overlaps IError (T is IError, object, or an error type): IError e also matches a successful value that is an error, and a T arm also matches a failure whose error is a T. Use IsSuccess or Match for those.
  • Implicit conversion follows the same overlap: an error assigned to a Result<object> becomes a failure, and assigning one to a Result<IError> does not compile. Success(...) and Failure(...) are always unambiguous.
  • IsSuccess, Value, Error, Match and property patterns such as result 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 when result is already typed Result<int>. Matching from object (obj is Result<int> r) is unaffected.
  • Result<T>.IUnionMembers is 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.

MethodDescription
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)
MethodDescription
SelectProjects a success value (backs select). Sync and async source overloads.
SelectManyBinds 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:

MethodDescription
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.

MethodDescription
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
MethodDescription
Result.From / Result.FromAsyncCreate 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.0 and netstandard2.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 — WhenNull and FromNullable genuinely narrow T? to T.
  • 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.
Something went wrong. This site returns Results, not exceptions — please reload. ✕