Public .NET API ReferenceL0 Foundation PrimitivesStableAOT: Partial

EricksonLopez.Result

A high-performance, zero-allocation Result Pattern ecosystem for modern .NET. Includes ASP.NET Core ProblemDetails, OpenTelemetry, MediatR, FluentValidation, and Roslyn Analyzer integrations.

20 namespaces83 types878 membersGenerated from XML docs & assemblies · UTC 2026-12-01

Showing 83 of 83 types (878 members)

EricksonLopez.Result#

14
class

Error

Assembly: EricksonLopez.Result
public sealed partial class Error
Implements: IEquatable<Error>

Represents a structured, immutable domain error with support for deep equality, metadata, retryability, and distributed tracing.

Remarks:

Design — sealed class: `Error` is `sealed` to guarantee correct equality semantics. A non-sealed error class allows subclasses to add domain-specific fields without overriding `Error.Equals(Error)` and `Error.GetHashCode`, which would silently break equality in `HashSet<Error>`, `Dictionary<Error, T>`, and `Result.Equals` comparisons. Extensibility via composition: Instead of subclassing, attach domain-specific context to an error using `Error.WithMetadata(string, object)` or the fluent `ErrorBuilder` API:

// ✅ Preferred — composition via metadata:
var error = Error.Create("Payment.Declined", "Payment was declined.")
    .WithType(ErrorType.Domain)
    .WithMetadata("transactionId", transactionId)
    .WithMetadata("gatewayCode", gatewayCode)
    .Build();

// ✅ Or use domain-specific factory methods:
public static class PaymentErrors
{
    public static Error Declined(string transactionId) =>
        Error.Create("Payment.Declined", "Payment was declined.")
            .WithType(ErrorType.Domain)
            .WithMetadata("transactionId", transactionId)
            .Build();
}

The constructor is `public` to allow direct construction. Prefer the static factory methods (`Error.Failure(string, string)`, `Error.Validation(string, string)`, etc.) or `Error.Create(string, string)` + `ErrorBuilder` for common patterns.

Members (83)

  • constructorError
    public Error(string code, string description, ErrorType type = ErrorType.Failure, ErrorSeverity severity = ErrorSeverity.Error, ErrorRetryability retryability = ErrorRetryability.NotApplicable, string? descriptionKey = null, string? traceId = null, string? correlationId = null, IReadOnlyList<Error>? innerErrors = null, IReadOnlyDictionary<string, object>? metadata = null)

    Initializes a new instance of the `Error` class.

    code: string
    The unique machine-readable error code. Must not be `null` or whitespace.
    description: string
    The human-readable description for diagnostic logging. Must not be `null` or whitespace.
    type: ErrorType
    The error category type. Defaults to `ErrorType.Failure`.
    severity: ErrorSeverity
    The error severity level. Defaults to `ErrorSeverity.Error`.
    retryability: ErrorRetryability
    The retry classification. Defaults to `ErrorRetryability.NotApplicable`.
    descriptionKey: string?
    The optional resource key for localized messages.
    traceId: string?
    The optional distributed trace identifier string.
    correlationId: string?
    The optional distributed correlation identifier string.
    innerErrors: IReadOnlyList<Error>?
    The optional collection of child errors composing this error.
    metadata: IReadOnlyDictionary<string, object>?
    The optional key-value metadata dictionary.

    ⚠️ Prefer factory methods over this constructor. Use `Failure(string, string)`, `Validation(string, string)`, `NotFound(string, string)`, or `Create(string, string)` + `ErrorBuilder` for fluent construction. This 10-parameter constructor is hidden from IntelliSense to avoid confusion, but remains public for advanced and serialization scenarios. When `traceId` is `null` and an ambient `Activity` is active, the current `Activity.TraceId` is captured as an `ActivityTraceId` struct (zero heap allocation). The string representation is materialized lazily only when `TraceId` is actually accessed. Exceptions: ArgumentException: `code` or `description` is `null`, empty, or consists only of white-space characters

  • methodBusiness
    public static Error Business(string code, string description)

    Creates a new `Error` representing a business rule or domain invariant violation (alias for `Domain`).

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Domain` type and `ErrorSeverity.Error` severity.

  • methodClearTraceId
    public Error ClearTraceId()

    Creates a new `Error` copy with the trace ID override cleared. After this call, `TraceId` will return the ambient `Activity.Current` trace ID (if any), or `null`.

    Returns: A new `Error` instance without a trace identifier override.

    This is a more intention-revealing alternative to `WithTraceId(null)`.

  • methodConflict
    public static Error Conflict(string code, string description)

    Creates a new `Error` representing a state conflict with existing resources.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Conflict` type and `ErrorSeverity.Warning` severity.

  • methodConflict
    public static Error Conflict(string code, string description, IReadOnlyDictionary<string, object> metadata)

    Creates a new `Error` representing a conflict with metadata.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.
    metadata: IReadOnlyDictionary<string, object>
    Structured key-value metadata associated with the error.

    Returns: A new `Error` instance with `ErrorType.Conflict` type.

  • methodCreate
    public static ErrorBuilder Create(string code, string description)

    Creates an `ErrorBuilder` initialized with the specified error code and description.

    code: string
    The unique machine-readable error code. Must not be `null` or whitespace.
    description: string
    The human-readable technical description. Must not be `null` or whitespace.

    Returns: An `ErrorBuilder` pre-seeded with the specified code and description.

    Example:

    var error = Error.Create("Order.Expired", "The order has expired.")
        .WithType(ErrorType.Domain)
        .WithSeverity(ErrorSeverity.Warning)
        .WithRetryability(ErrorRetryability.Permanent)
        .WithCorrelationId(correlationId)
        .WithMetadata("orderId", orderId)
        .Build();
  • methodCustom
    public static Error Custom(string code, string description, ErrorType type, ErrorSeverity severity, ErrorRetryability retryability, IReadOnlyDictionary<string, object>? metadata, params Error[] innerErrors)

    Creates a custom error with specified metadata and child errors.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.
    type: ErrorType
    The error category type.
    severity: ErrorSeverity
    The error severity level.
    retryability: ErrorRetryability
    The retry classification.
    metadata: IReadOnlyDictionary<string, object>?
    The optional key-value metadata dictionary.
    innerErrors: params Error[]
    The child errors composing this error.

    Returns: A new `Error` instance configured with the specified attributes.

    For most use cases, prefer `Create(string, string)` with the fluent `ErrorBuilder` pattern.

  • methodCustom
    public static Error Custom(string code, string description, ErrorType type, ErrorSeverity severity = ErrorSeverity.Error, ErrorRetryability retryability = ErrorRetryability.NotApplicable, string? descriptionKey = null, string? traceId = null, string? correlationId = null, IReadOnlyList<Error>? innerErrors = null, IReadOnlyDictionary<string, object>? metadata = null)

    Creates a custom error with specified attributes.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.
    type: ErrorType
    The error category type.
    severity: ErrorSeverity
    The error severity level. Defaults to `ErrorSeverity.Error`.
    retryability: ErrorRetryability
    The retry classification. Defaults to `ErrorRetryability.NotApplicable`.
    descriptionKey: string?
    The optional resource key for localized messages.
    traceId: string?
    The optional distributed trace identifier string.
    correlationId: string?
    The optional distributed correlation identifier string.
    innerErrors: IReadOnlyList<Error>?
    The optional collection of child errors composing this error.
    metadata: IReadOnlyDictionary<string, object>?
    The optional key-value metadata dictionary.

    Returns: A new `Error` instance configured with the specified attributes.

    For most use cases, prefer `Create(string, string)` with the fluent `ErrorBuilder` pattern.

  • methodDomain
    public static Error Domain(string code, string description)

    Creates a new `Error` representing a business rule or domain invariant violation.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Domain` type and `ErrorSeverity.Error` severity.

  • methodEquals
    public bool Equals(Error? other)

    Determines whether this error is semantically equal to another `Error` based on `Code`, `Description`, `Type`, `Severity`, `Retryability`, and constituent `InnerErrors`.

    other: Error?
    The other `Error` to compare with this instance.

    Returns: `true` if both errors share the same semantic values; otherwise, `false`.

    This is a semantic equality check. Per-request diagnostic/contextual fields are intentionally excluded because they vary per request and do not determine whether two errors represent the same logical failure: `TraceId`, `CorrelationId`, `DescriptionKey`, and `Metadata`. `Retryability` and `InnerErrors` ARE included because they define the logical failure semantics (preventing unrelated composite errors produced by `Result.Combine(ReadOnlySpan<Result>)` from colliding or silently deduplicating in `HashSet<T>`). Use `StrictEquals` for deep structural equality that includes all fields including `TraceId`, `CorrelationId`, `Metadata`, and `InnerErrors`. Exceptions: InvalidOperationException: The `InnerErrors` hierarchy exceeds the maximum recursion depth of 32

  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodFailure
    public static Error Failure(string code, string description)

    Creates a new `Error` representing a general failure.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Failure` type and `ErrorSeverity.Error` severity.

  • methodFailure
    public static Error Failure(string code, string description, params Error[] innerErrors)

    Creates a new `Error` representing a general failure wrapping child errors.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.
    innerErrors: params Error[]
    The child errors caused by or contributing to this failure.

    Returns: A new `Error` instance containing the specified child errors.

  • methodForbidden
    public static Error Forbidden(string code, string description)

    Creates a new `Error` representing an authorization or permission denial failure.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Forbidden` type and `ErrorSeverity.Error` severity.

  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

    `GetHashCode` is computed from `Code`, `Description`, `Type`, `Severity`, `Retryability`, and when present, the constituent semantic fields of `InnerErrors` (bounded to `32` levels) so that composite errors with distinct constituent failures produce distinct hash codes. Per-request fields (`TraceId`, `CorrelationId`, `DescriptionKey`, `Metadata`) are excluded to match `Equals(Error?)`. Use `ErrorEqualityComparer` with `ErrorEqualityComparer.Strict` for deep structural equality (including trace IDs and metadata) in collections, or use `StrictEquals` when comparing individual error instances.

  • methodGetMetadata<T>
    public T GetMetadata<T>(string key)

    Retrieves a metadata value by key and casts it to the specified type.

    key: string
    The metadata key to look up. Must not be `null` or whitespace.

    Returns: The metadata value cast to `T`.

    Type parameters: T: The expected type of the metadata value. Exceptions: ArgumentException: `key` is `null`, empty, or consists only of white-space characters; KeyNotFoundException: The metadata key does not exist in this error; InvalidCastException: The metadata key exists but the stored value is `null` or cannot be cast to `T`

  • methodInfrastructure
    public static Error Infrastructure(string code, string description)

    Creates a new `Error` representing an infrastructure, network, or database connectivity failure.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Infrastructure` type, `ErrorSeverity.Error` severity, and `ErrorRetryability.Transient` retryability.

  • methodNotFound
    public static Error NotFound(string entityName, object key)

    Creates a new `Error` representing an entity not found with a key.

    entityName: string
    key: object
  • methodNotFound
    public static Error NotFound(string code, string description)

    Creates a new `Error` representing a missing or nonexistent resource.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.NotFound` type and `ErrorSeverity.Warning` severity.

  • methodNotFound<TId>
    public static Error NotFound<TId>(string entity, TId id) where TId : struct

    Creates a new `Error` representing an entity not found with a strongly-typed ID.

    entity: string
    The entity name.
    id: TId
    The strongly-typed identifier value.

    Returns: A new `Error` instance with `ErrorType.NotFound` type.

    Type parameters: TId: The strongly-typed identifier type.

  • methodStrictEquals
    public bool StrictEquals(Error? other)

    Performs deep structural equality checking including all fields: `Code`, `Description`, `Type`, `Severity`, `Retryability`, `TraceId`, `CorrelationId`, `DescriptionKey`, `InnerErrors`, and `Metadata`.

    other: Error?
    The other `Error` to compare with this instance.

    Returns: `true` if all fields and metadata match exactly; otherwise, `false`.

    Exceptions: InvalidOperationException: The `InnerErrors` hierarchy exceeds the maximum recursion depth of 32

  • methodToBuilder
    public ErrorBuilder ToBuilder()

    Creates an `ErrorBuilder` pre-seeded with all fields of this `Error`, allowing efficient construction of a modified copy without chaining multiple `With*` calls (which each copy the full Error state).

    Returns: An `ErrorBuilder` configured with this error's state.

    Example:

    var enriched = existingError.ToBuilder()
        .WithMetadata("requestId", requestId)
        .WithMetadata("userId", userId)
        .Build();
  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTryGetMetadata<T>
    public bool TryGetMetadata<T>(string key, out T? value)

    Attempts to retrieve a metadata value by key and cast it to the specified type.

    key: string
    The metadata key to look up. Must not be `null` or whitespace.
    value: out T?
    When this method returns, contains the metadata value cast to `T` if found and valid; otherwise, the default value for the type.

    Returns: `true` if the key exists and its value can be cast to `T`; otherwise, `false` if the key is not found or its value is `null`.

    ⚠️ Post-deserialization type narrowing: JSON deserialization via `EricksonLopez.Result.Serialization` narrows metadata types: - JSON integers → `long` (not `int`) - `Guid`, `DateTime` → `string` - Only `bool`, `long`, `double`, and `string` survive a JSON round-trip without type loss. Type parameters: T: The expected type of the metadata value. Exceptions: ArgumentException: `key` is `null`, empty, or consists only of white-space characters; InvalidCastException: The metadata key exists but the stored value cannot be cast to `T` Example:

    // After JSON round-trip, int is stored as long:
    if (error.TryGetMetadata<long>("orderId", out var id))
        Console.WriteLine(id);
    
    // In-memory (no round-trip), original types are preserved:
    if (error.TryGetMetadata<Guid>("correlationId", out var guid))
        Console.WriteLine(guid);
  • methodUnauthorized
    public static Error Unauthorized(string description)

    Creates a new `Error` representing an unauthenticated request requiring authentication.

    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Unauthorized` type and `ErrorSeverity.Error` severity.

  • methodUnauthorized
    public static Error Unauthorized(string code, string description)

    Creates a new `Error` representing an unauthenticated request requiring authentication.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Unauthorized` type and `ErrorSeverity.Error` severity.

  • methodUnavailable
    public static Error Unavailable(string code, string description)

    Creates a new `Error` representing a transient external service unavailability failure.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Unavailable` type, `ErrorSeverity.Error` severity, and `ErrorRetryability.Transient` retryability.

  • methodUnexpected
    public static Error Unexpected(string code, string description)

    Creates a new `Error` representing an unexpected critical system failure.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Unexpected` type and `ErrorSeverity.Critical` severity.

  • methodValidation
    public static Error Validation(string code, string description)

    Creates a new `Error` representing an input validation failure.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.

    Returns: A new `Error` instance with `ErrorType.Validation` type and `ErrorSeverity.Warning` severity.

  • methodValidation
    public static Error Validation(string code, string description, params Error[] innerErrors)

    Creates a new `Error` representing an input validation failure wrapping child errors.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.
    innerErrors: params Error[]
    The validation child errors.

    Returns: A new `Error` instance containing the specified child errors.

  • methodValidation
    public static Error Validation(string code, string description, IReadOnlyDictionary<string, object> metadata)

    Creates a new `Error` representing an input validation failure with metadata.

    code: string
    The unique machine-readable error code.
    description: string
    The human-readable technical description.
    metadata: IReadOnlyDictionary<string, object>
    Structured key-value metadata associated with the error.

    Returns: A new `Error` instance with `ErrorType.Validation` type.

  • methodWithCategory
    public Error WithCategory(string? category)

    Creates a new `Error` copy with the specified category metadata.

    category: string?
    The error category name.

    Returns: A new `Error` instance with the category metadata attached.

  • methodWithCorrelationId
    public Error WithCorrelationId(string? correlationId)

    Creates a new `Error` copy with the specified correlation identifier.

    correlationId: string?
    The correlation identifier to associate with the error, or `null` to clear it.

    Returns: A new `Error` instance with the updated correlation identifier.

  • methodWithDescriptionKey
    public Error WithDescriptionKey(string? descriptionKey)

    Creates a new `Error` copy with the specified localization description key.

    descriptionKey: string?
    The localization resource key, or `null` to clear it.

    Returns: A new `Error` instance with the updated description key.

  • methodWithDetails
    public Error WithDetails(object? details)

    Creates a new `Error` copy with the specified additional diagnostic details.

    details: object?
    The diagnostic details dictionary or object.

    Returns: A new `Error` instance with the details metadata attached.

  • methodWithDocumentationUrl
    public Error WithDocumentationUrl(string? documentationUrl)

    Creates a new `Error` copy with the specified documentation URL.

    documentationUrl: string?
    The documentation URL.

    Returns: A new `Error` instance with the documentation URL attached.

  • methodWithHttpStatus
    public Error WithHttpStatus(int? httpStatus)

    Creates a new `Error` copy with the specified HTTP status code.

    httpStatus: int?
    The HTTP status code (e.g. 400, 401, 404, 429).

    Returns: A new `Error` instance with the HTTP status metadata attached.

  • methodWithInnerError
    public Error WithInnerError(Error? innerError)

    Creates a new `Error` copy with the specified inner causal error attached.

    innerError: Error?
    The causal inner error, if any.

    Returns: A new `Error` instance with the inner error attached.

  • methodWithIsRetryable
    public Error WithIsRetryable(bool isRetryable)

    Creates a new `Error` copy with the specified boolean retryability flag and corresponding `ErrorRetryability`.

    isRetryable: bool
    Whether the operation can be retried.

    Returns: A new `Error` instance with retryability configured.

  • methodWithMetadata
    public Error WithMetadata(IEnumerable<KeyValuePair<string, object>> metadata)

    Creates a new `Error` copy containing the specified metadata entries from an enumerable source.

    metadata: IEnumerable<KeyValuePair<string, object>>
    The sequence of metadata entries to add. Cannot be `null`.

    Returns: A new `Error` instance containing the merged metadata entries.

    This overload adds all entries in a single Error copy, using `ImmutableDictionary.Builder` to batch all additions before calling `ToImmutable()` once. Prefer this over chaining individual `WithMetadata(string, object)` calls when adding multiple entries. Exceptions: ArgumentNullException: `metadata` is `null`

  • methodWithMetadata
    public Error WithMetadata(IReadOnlyDictionary<string, object> metadata)

    Creates a new `Error` copy containing the specified metadata entries.

    metadata: IReadOnlyDictionary<string, object>
    The dictionary of metadata entries to add. Cannot be `null`.

    Returns: A new `Error` instance containing the merged metadata entries.

    This overload adds all entries in a single Error copy, using `ImmutableDictionary.Builder` to batch all additions before calling `ToImmutable()` once. Prefer this over chaining individual `WithMetadata(string, object)` calls when adding multiple entries. Exceptions: ArgumentNullException: `metadata` is `null`

  • methodWithMetadata
    public Error WithMetadata(string key, object value)

    Creates a new `Error` copy containing the specified metadata entry.

    key: string
    The metadata key to add or update. Must not be `null` or whitespace.
    value: object
    The metadata value to associate with the key.

    Returns: A new `Error` instance with the added or updated metadata entry.

    ⚠️ Performance Warning: Each call to `WithMetadata` creates a new `Error` instance and a new `Immutable.ImmutableDictionary<TKey, TValue>` snapshot. Internally, this uses `ImmutableDictionary.Builder`: the add operation is O(log k) and `ToImmutable()` is O(k) where k is the current metadata count. Additionally, each call copies all 10 fields of `Error`. Chaining n calls (e.g., `.WithMetadata("a", 1).WithMetadata("b", 2).WithMetadata("c", 3)`) creates n intermediate Error copies — O(n·k) total cost, not O(n²) in the dictionary. For multiple metadata entries, use one of these alternatives: - `WithMetadata(IReadOnlyDictionary<string, object>)` — batch overload, single Error copy. - `WithMetadata(IEnumerable<KeyValuePair<string, object>>)` — enumerable overload, single Error copy. - `ToBuilder` → `ErrorBuilder.WithMetadata(string, object)` (repeated) → `ErrorBuilder.Build` — zero intermediate Error copies. Exceptions: ArgumentException: `key` is `null`, empty, or consists only of white-space characters

  • methodWithRequestId
    public Error WithRequestId(Guid? requestId)

    Creates a new `Error` copy with the specified request identifier GUID.

    requestId: Guid?
    The request identifier GUID.

    Returns: A new `Error` instance with the request identifier metadata attached.

  • methodWithRequestId
    public Error WithRequestId(string? requestId)

    Creates a new `Error` copy with the specified request identifier.

    requestId: string?
    The request identifier string.

    Returns: A new `Error` instance with the request identifier metadata attached.

  • methodWithRetryAfter
    public Error WithRetryAfter(TimeSpan? retryAfter)

    Creates a new `Error` copy with the specified retry-after duration.

    retryAfter: TimeSpan?
    The cooldown timespan before retrying.

    Returns: A new `Error` instance with the retry-after metadata attached.

  • methodWithRetryability
    public Error WithRetryability(ErrorRetryability retryability)

    Creates a new `Error` copy with the specified retryability classification.

    retryability: ErrorRetryability
    The retry classification to apply.

    Returns: A new `Error` instance with the updated retryability classification.

  • methodWithSdkVersion
    public Error WithSdkVersion(string? sdkVersion)

    Creates a new `Error` copy with the specified SDK version.

    sdkVersion: string?
    The version of the emitting SDK.

    Returns: A new `Error` instance with the SDK version metadata attached.

  • methodWithSuggestedAction
    public Error WithSuggestedAction(string? suggestedAction)

    Creates a new `Error` copy with the specified suggested action or user remediation instruction.

    suggestedAction: string?
    The recommended resolution action.

    Returns: A new `Error` instance with the suggested action metadata attached.

  • methodWithTimestamp
    public Error WithTimestamp(DateTimeOffset? timestamp)

    Creates a new `Error` copy with the specified timestamp.

    timestamp: DateTimeOffset?
    The exact moment the error occurred.

    Returns: A new `Error` instance with the timestamp metadata attached.

  • methodWithTraceId
    public Error WithTraceId(ActivityTraceId traceId)

    Creates a new `Error` copy with the specified strongly-typed `ActivityTraceId`. Avoids string allocation compared to `WithTraceId(string?)`.

    traceId: ActivityTraceId
    The strongly-typed OpenTelemetry trace identifier.

    Returns: A new `Error` instance with the updated trace identifier.

  • methodWithTraceId
    public Error WithTraceId(string? traceId)

    Creates a new `Error` copy with the specified OpenTelemetry trace identifier string. This overrides both the ambient `Activity` trace ID and any previously captured value.

    traceId: string?
    The distributed trace identifier string, or `null` to clear the override.

    Returns: A new `Error` instance with the updated trace identifier.

    ⚠️ Note: Passing `null` clears the trace ID override, removing it from serialized output and reverting to the ambient `Activity.Current` behavior. To explicitly clear the trace ID with a more intention-revealing call, use `ClearTraceId()`. To set a strongly-typed `ActivityTraceId` directly without string allocation, use `WithTraceId(ActivityTraceId)`.

  • methodWithValidationErrors
    public Error WithValidationErrors(object? validationErrors)

    Creates a new `Error` copy with the specified granular field validation errors.

    validationErrors: object?
    The collection or object representing field-level errors.

    Returns: A new `Error` instance with the validation errors metadata attached.

  • methodimplicit operator string
    public static implicit operator string(Error error)

    Implicit conversion to string returning the error code.

    error: Error
  • methodoperator !=
    public static bool operator !=(Error? left, Error? right)

    Determines whether two `Error` instances are not equal.

    left: Error?
    The first error to compare.
    right: Error?
    The second error to compare.

    Returns: `true` if the instances are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(Error? left, Error? right)

    Determines whether two `Error` instances are semantically equal.

    left: Error?
    The first error to compare.
    right: Error?
    The second error to compare.

    Returns: `true` if both instances are equal; otherwise, `false`.

    Checks `ReferenceEquals` first (fast path for same-instance comparisons), then delegates to `Equals(Error?)` for semantic equality.

  • propertyCategory
    public string Category { get; }

    Gets the domain or regulatory error category string, if specified in metadata, or falls back to `Type` name.

  • propertyCode
    public string Code { get; }

    Gets the unique machine-readable error code.

  • propertyCorrelationId
    public string? CorrelationId { get; }

    Gets the distributed correlation identifier associated with this error.

  • propertyDescription
    public string Description { get; }

    Gets the technical description of the error for diagnostics and logging.

  • propertyDescriptionKey
    public string? DescriptionKey { get; }

    Gets the optional localization resource key for the error message.

  • propertyDetails
    public object? Details { get; }

    Gets the semi-structured additional diagnostic details dictionary, if specified.

  • propertyDocumentationUrl
    public string? DocumentationUrl { get; }

    Gets the official documentation or resolution URL for this error, if specified.

  • propertyHasInnerErrors
    public bool HasInnerErrors { get; }

    Gets a value indicating whether this error contains one or more child errors.

  • propertyHasMetadata
    public bool HasMetadata { get; }

    Gets a value indicating whether this error contains metadata entries.

  • propertyHttpStatus
    public int? HttpStatus { get; }

    Gets the HTTP status code associated with this error (e.g. 400, 401, 404, 429), if specified.

  • propertyInnerError
    public Error? InnerError { get; }

    Gets the primary inner causal `Error` if any inner errors are attached; otherwise `null`.

  • propertyInnerErrors
    public ImmutableArray<Error> InnerErrors { get; }

    Gets the immutable list of inner errors composing this error.

    Returns `ImmutableArray<T>.Empty` when there are no inner errors — never `null`. Common patterns: - Check for inner errors: `if (error.HasInnerErrors)` (preferred) or `if (!error.InnerErrors.IsEmpty)` - Iterate: `foreach (var inner in error.InnerErrors)` - LINQ: `error.InnerErrors.Any(e => e.Code == "...")` — note: requires `using System.Linq` ⚠️ Migration note: this property changed from `IReadOnlyList<Error>` to `ImmutableArray<Error>`. If you store the result in a variable, update the declared type from `IReadOnlyList<Error>` to `ImmutableArray<Error>` or `var`. The `Count`, indexer, and `foreach` patterns remain unchanged.

  • propertyIsRetryable
    public bool IsRetryable { get; }

    Gets a value indicating whether the operation that caused this error is retryable. Evaluates explicit metadata if present, or derives from `Retryability`.

  • propertyMessage
    public string Message { get; }

    Gets the descriptive message for the error (alias for `Description`).

  • propertyMetadata
    public IReadOnlyDictionary<string, object> Metadata { get; }

    Gets the immutable key-value metadata dictionary associated with this error.

    Metadata values accept any `object` and are stored as-is in memory. Prefer simple, serializable types (`string`, `int`, `bool`, `Guid`) for values you intend to serialize. ⚠️ Serialization type-loss warning: When this error is serialized and deserialized using the `EricksonLopez.Result.Serialization` package (`ErrorJsonConverter`), metadata values undergo type narrowing: - JSON numbers are deserialized as `long` or `double` — casting `(int)error.Metadata["orderId"]` will throw `System.InvalidCastException`. - `Guid`, `DateTime`, and other complex types are serialized as strings and deserialized as `string` — casting back to the original type will throw. - Only `bool`, `long`, `double`, and `string` round-trip without loss. Design metadata with this constraint in mind, or avoid relying on type-specific casts after deserialization.

  • propertyRequestId
    public string? RequestId { get; }

    Gets the distributed request identifier associated with this error, if specified.

  • propertyRetryAfter
    public TimeSpan? RetryAfter { get; }

    Gets the cooldown duration before the operation may be retried (for rate-limiting / HTTP 429), if specified.

  • propertyRetryability
    public ErrorRetryability Retryability { get; }

    Gets the retry classification indicating whether the operation may be retried.

  • propertySdkVersion
    public string? SdkVersion { get; }

    Gets the immutable SDK version that generated this error, if specified.

  • propertySeverity
    public ErrorSeverity Severity { get; }

    Gets the severity level of the error.

  • propertySuggestedAction
    public string? SuggestedAction { get; }

    Gets the prescriptive suggested action or remediation instructions for this error, if specified.

  • propertyTimestamp
    public DateTimeOffset? Timestamp { get; }

    Gets the exact timestamp when this error occurred, if specified.

  • propertyTraceId
    public string? TraceId { get; }

    Gets the OpenTelemetry trace identifier associated with this error. The string is materialized lazily on first access and cached to avoid repeated heap allocations for the 32-character trace ID string in concurrent scenarios.

  • propertyType
    public ErrorType Type { get; }

    Gets the classification category of the error.

  • propertyValidationErrors
    public object? ValidationErrors { get; }

    Gets the granular field-level validation errors object or collection, if specified.

  • fieldNone
    public static readonly Error None

    Represents a sentinel non-error or empty error instance.

  • fieldNullValue
    public static readonly Error NullValue

    Represents a `null` value error instance.

  • fieldValidationError
    public static readonly Error ValidationError

    Represents a standard validation error instance.

struct

ErrorBuilder

Assembly: EricksonLopez.Result
public readonly partial struct ErrorBuilder

Represents a fluent, stack-allocated builder for constructing `Error` instances with multiple optional properties. The builder struct itself incurs no heap allocation; however, `ErrorBuilder.WithMetadata(string, object)` and `ErrorBuilder.WithInnerError(Error)` allocate heap nodes in the backing `ImmutableDictionary<T1, T2>` and `ImmutableArray<T>` respectively (O(log k) per entry for metadata). Prefer this over the `Error` constructor when setting more than two optional fields, or use `Error.ToBuilder` to create a modified copy of an existing `Error`.

Remarks:

Value type semantics: `ErrorBuilder` is a `readonly struct` to avoid heap allocation. Each `With*` method returns a modified copy of the builder. Always use it in a fluent chain or reassign the return value:

var error = Error.Create("Order.Expired", "The order has expired.")
    .WithType(ErrorType.Domain)
    .WithSeverity(ErrorSeverity.Warning)
    .WithRetryability(ErrorRetryability.Permanent)
    .WithCorrelationId(correlationId)
    .WithMetadata("orderId", orderId)
    .Build();

⚠ Copy cost per `With*()` call: `ErrorBuilder` is approximately 96–104 bytes in size (11 fields including an `ImmutableDictionary` reference, an `ImmutableArray` reference, two string references for trace ID, and several enum byte fields). Each `With*()` call copies the entire struct to produce a new instance. A fluent chain of N calls copies the struct N times (e.g., a 5-step chain copies ~500 bytes total on the stack). This is cheaper than N heap allocations but is measurably more expensive than a single mutation. For hot paths where error construction occurs in a tight loop, consider: - Pre-building the `Error` once (outside the loop) if the error is reused. - Using `ErrorBuilder.WithMetadata(IEnumerable<KeyValuePair<string, object>>)` to batch multiple metadata entries in a single call instead of chaining individual `WithMetadata(string, object)` calls. - Using `ErrorBuilder.WithInnerErrors(IEnumerable<Error>)` instead of multiple `ErrorBuilder.WithInnerError(Error)` calls to avoid O(n²) `ImmutableArray` copying. For non-hot-path code (startup, exception handling, validation), the copy cost is negligible. Because this is a `readonly struct`, discarding the return value of a `With*` method has no effect on the builder instance — the mutated copy is silently lost. The `RESULT003` Roslyn analyzer (from the `EricksonLopez.Result.Analyzers` package) detects this pattern and reports an error diagnostic. A companion `CodeFixProvider` provides an Alt+Enter fix to rewrite the statement as an assignment. Without the analyzer installed, discarding a `With*` return value compiles without any diagnostic. Obtain an instance via `Error.Create(string, string)` for new errors, or via `Error.ToBuilder` to mutate an existing error efficiently. Thread Safety: Not thread-safe. Use from a single thread only.

Members (24)

  • methodBuild
    public Error Build()

    Creates the configured immutable `Error` instance.

    Returns: A new `Error` instance configured with the builder state.

    The builder can be called multiple times; each call creates a new `Error` snapshot. The builder state is not mutated by `Build()`. Uses an internal fast path (`Error.CreateFromBuilder`) that skips argument validation (already enforced by the factory method that created the builder) and avoids re-capturing `Activity.Current`. If the builder holds a raw `ActivityTraceId` struct (from `FromError` or `WithTraceId(ActivityTraceId)`), it is materialized to a string at this point — exactly once per `Build()` call. Exceptions: InvalidOperationException: The builder is an uninitialized `default(ErrorBuilder)` value

  • methodWithCategory
    public ErrorBuilder WithCategory(string? category)

    Attaches a category string to the error being built.

    category: string?
    The error category name.

    Returns: A new `ErrorBuilder` instance with the category metadata attached.

  • methodWithCorrelationId
    public ErrorBuilder WithCorrelationId(string? correlationId)

    Sets the distributed correlation identifier on the error being built.

    correlationId: string?
    The correlation identifier to associate with the error, or `null` to clear it.

    Returns: A new `ErrorBuilder` instance with the specified correlation identifier.

  • methodWithDescriptionKey
    public ErrorBuilder WithDescriptionKey(string? descriptionKey)

    Sets the localization resource key on the error being built.

    descriptionKey: string?
    The localization resource key, or `null` to clear it.

    Returns: A new `ErrorBuilder` instance with the specified description key.

  • methodWithDetails
    public ErrorBuilder WithDetails(object? details)

    Attaches semi-structured diagnostic details to the error being built.

    details: object?
    The diagnostic details dictionary or object.

    Returns: A new `ErrorBuilder` instance with the details metadata attached.

  • methodWithDocumentationUrl
    public ErrorBuilder WithDocumentationUrl(string? documentationUrl)

    Attaches an official documentation or resolution URL to the error being built.

    documentationUrl: string?
    The documentation URL.

    Returns: A new `ErrorBuilder` instance with the documentation URL attached.

  • methodWithHttpStatus
    public ErrorBuilder WithHttpStatus(int? httpStatus)

    Attaches an HTTP status code to the error being built.

    httpStatus: int?
    The HTTP status code (e.g. 400, 401, 404, 429).

    Returns: A new `ErrorBuilder` instance with the HTTP status metadata attached.

  • methodWithInnerError
    public ErrorBuilder WithInnerError(Error innerError)

    Appends a child error to the error being built.

    innerError: Error
    The child error to add.

    Returns: A new `ErrorBuilder` instance containing the added child error.

    Uses `ImmutableArray<T>.Add` which creates a new array of size n+1 and copies all existing elements — this is O(n) per call, resulting in O(n²) total cost when chaining multiple `WithInnerError` calls. For bulk inner error construction, prefer `WithInnerErrors` which uses `ImmutableArray<T>.AddRange` for a single copy operation. This is still preferable to the previous `new List<Error>(existing)` approach because ImmutableArray avoids the mutable List overhead and integrates cleanly with the copy-on-write ErrorBuilder semantics.

  • methodWithInnerErrors
    public ErrorBuilder WithInnerErrors(IEnumerable<Error> innerErrors)

    Appends a collection of child errors to the error being built.

    innerErrors: IEnumerable<Error>
    The collection of child errors to add.

    Returns: A new `ErrorBuilder` instance containing the added child errors.

    Uses `ImmutableArray<T>.AddRange` to append all elements in a single structural operation, avoiding repeated intermediate copies. Recommended practice is to restrict inner errors to < 100 entries to minimize memory footprint.

  • methodWithIsRetryable
    public ErrorBuilder WithIsRetryable(bool isRetryable)

    Configures whether the error being built represents a retryable operation.

    isRetryable: bool
    Whether the operation can be retried.

    Returns: A new `ErrorBuilder` instance with retryability configured.

  • methodWithMetadata
    public ErrorBuilder WithMetadata(IEnumerable<KeyValuePair<string, object>> entries)

    Adds multiple metadata key-value pairs in a single operation, avoiding repeated intermediate allocations.

    entries: IEnumerable<KeyValuePair<string, object>>
    The collection of metadata entries to add.

    Returns: A new `ErrorBuilder` instance containing the merged metadata.

  • methodWithMetadata
    public ErrorBuilder WithMetadata(string key, object value)

    Adds or updates a single metadata key-value pair on the error being built.

    key: string
    The metadata key to add or update.
    value: object
    The metadata value to store.

    Returns: A new `ErrorBuilder` instance containing the updated metadata.

  • methodWithRequestId
    public ErrorBuilder WithRequestId(Guid? requestId)

    Attaches a request identifier GUID to the error being built.

    requestId: Guid?
    The request identifier GUID.

    Returns: A new `ErrorBuilder` instance with the request identifier metadata attached.

  • methodWithRequestId
    public ErrorBuilder WithRequestId(string? requestId)

    Attaches a request identifier string to the error being built.

    requestId: string?
    The request identifier string.

    Returns: A new `ErrorBuilder` instance with the request identifier metadata attached.

  • methodWithRetryAfter
    public ErrorBuilder WithRetryAfter(TimeSpan? retryAfter)

    Attaches a cooldown retry-after duration to the error being built.

    retryAfter: TimeSpan?
    The cooldown timespan before retrying.

    Returns: A new `ErrorBuilder` instance with the retry-after metadata attached.

  • methodWithRetryability
    public ErrorBuilder WithRetryability(ErrorRetryability retryability)

    Sets the retry classification for the error being built.

    retryability: ErrorRetryability
    The retry classification to assign.

    Returns: A new `ErrorBuilder` instance with the specified retryability.

  • methodWithSdkVersion
    public ErrorBuilder WithSdkVersion(string? sdkVersion)

    Attaches an emitting SDK version to the error being built.

    sdkVersion: string?
    The version of the emitting SDK.

    Returns: A new `ErrorBuilder` instance with the SDK version metadata attached.

  • methodWithSeverity
    public ErrorBuilder WithSeverity(ErrorSeverity severity)

    Sets the severity level for the error being built.

    severity: ErrorSeverity
    The error severity level to assign.

    Returns: A new `ErrorBuilder` instance with the specified severity level.

  • methodWithSuggestedAction
    public ErrorBuilder WithSuggestedAction(string? suggestedAction)

    Attaches a prescriptive suggested action or remediation instructions to the error being built.

    suggestedAction: string?
    The recommended resolution action.

    Returns: A new `ErrorBuilder` instance with the suggested action metadata attached.

  • methodWithTimestamp
    public ErrorBuilder WithTimestamp(DateTimeOffset? timestamp)

    Attaches an exact occurrence timestamp to the error being built.

    timestamp: DateTimeOffset?
    The exact moment the error occurred.

    Returns: A new `ErrorBuilder` instance with the timestamp metadata attached.

  • methodWithTraceId
    public ErrorBuilder WithTraceId(ActivityTraceId traceId)

    Sets a strongly-typed `ActivityTraceId` on the error being built without allocating a string — the struct is materialized to a string only when `Build` is called.

    traceId: ActivityTraceId
    The strongly-typed OpenTelemetry trace identifier.

    Returns: A new `ErrorBuilder` instance with the specified trace identifier.

  • methodWithTraceId
    public ErrorBuilder WithTraceId(string? traceId)

    Sets an explicit distributed trace identifier string on the error being built.

    traceId: string?
    The distributed trace identifier string, or `null` to clear the override.

    Returns: A new `ErrorBuilder` instance with the specified trace identifier.

    Prefer the `WithTraceId(ActivityTraceId)` overload when working with `Activity.Current` to avoid a premature `ActivityTraceId.ToString` allocation.

  • methodWithType
    public ErrorBuilder WithType(ErrorType type)

    Sets the category type for the error being built.

    type: ErrorType
    The error category type to assign.

    Returns: A new `ErrorBuilder` instance with the specified error type.

  • methodWithValidationErrors
    public ErrorBuilder WithValidationErrors(object? validationErrors)

    Attaches granular field validation errors to the error being built.

    validationErrors: object?
    The collection or object representing field-level errors.

    Returns: A new `ErrorBuilder` instance with the validation errors metadata attached.

class

ErrorEqualityComparer

Assembly: EricksonLopez.Result
public static class ErrorEqualityComparer

Provides `IEqualityComparer<T>` implementations for `Error`.

Remarks:

By default, `Error.Equals(Error?)` performs semantic equality based on `Error.Code`, `Error.Description`, `Error.Type`, `Error.Severity`, `Error.Retryability`, and `Error.InnerErrors`. Use `Strict` when you need full structural equality including `Error.TraceId`, `Error.CorrelationId`, `Error.DescriptionKey`, `Error.InnerErrors`, and `Error.Metadata`. Usage with collections:

var set = new HashSet<Error>(ErrorEqualityComparer.Strict);
var dict = new Dictionary<Error, int>(ErrorEqualityComparer.Strict);

Members (2)

  • propertyDefault
    public static IEqualityComparer<Error> Default { get; }

    Gets an `IEqualityComparer<T>` that uses `Error.Equals(Error?)` for semantic (Code, Description, Type, Severity, Retryability, InnerErrors) equality.

  • propertyStrict
    public static IEqualityComparer<Error> Strict { get; }

    Gets an `IEqualityComparer<T>` that uses `Error.StrictEquals` for deep structural equality including all fields (TraceId, CorrelationId, DescriptionKey, InnerErrors, Metadata) beyond those covered by shallow equality.

enum

ErrorRetryability

Assembly: EricksonLopez.Result
public enum ErrorRetryability : byte

Specifies whether an operation associated with an error can be retried.

Members (3)

  • fieldNotApplicable
    NotApplicable = 0

    Specifies that retry semantics do not apply to this error.

  • fieldPermanent
    Permanent = 2

    Specifies a deterministic failure that will not succeed upon retry.

  • fieldTransient
    Transient = 1

    Specifies a temporary failure that may succeed if retried.

enum

ErrorSeverity

Assembly: EricksonLopez.Result
public enum ErrorSeverity : byte

Specifies the severity level of an error.

Members (4)

  • fieldCritical
    Critical = 3

    Specifies a catastrophic failure requiring urgent intervention.

  • fieldError
    Error = 2

    Specifies a standard operational error or business failure.

  • fieldInfo
    Info = 0

    Specifies an informational event that does not disrupt execution.

  • fieldWarning
    Warning = 1

    Specifies a non-critical condition or expected failure.

enum

ErrorType

Assembly: EricksonLopez.Result
public enum ErrorType : byte

Specifies the classification category and functional scope of an error.

Members (11)

  • fieldConflict
    Conflict = 3

    Specifies a state conflict with the current state of a resource.

  • fieldCustom
    Custom = 10

    Specifies an application-specific custom error category.

  • fieldDomain
    Domain = 8

    Specifies a business rule or domain invariant violation.

  • fieldFailure
    Failure = 0

    Specifies a general unclassified failure.

  • fieldForbidden
    Forbidden = 5

    Specifies an authorization or permission denial failure.

  • fieldInfrastructure
    Infrastructure = 9

    Specifies an infrastructure, network, or database connectivity failure.

  • fieldNotFound
    NotFound = 2

    Specifies a missing or nonexistent resource failure.

  • fieldUnauthorized
    Unauthorized = 4

    Specifies an authentication requirement or failure.

  • fieldUnavailable
    Unavailable = 6

    Specifies a transient external service unavailability failure.

  • fieldUnexpected
    Unexpected = 7

    Specifies an unexpected internal or critical system failure.

  • fieldValidation
    Validation = 1

    Specifies an input validation or contract violation failure.

interface

IResultFactory<TSelf>

Assembly: EricksonLopez.Result
public interface IResultFactory<TSelf> : IResultOutcome where TSelf : IResultFactory<TSelf>
Implements: IResultOutcome

Defines a compile-time factory contract for constructing strongly-typed failed result outcomes without runtime reflection or boxing inside generic pipeline behaviors.

Remarks:

Type parameters: TSelf: The concrete result type implementing the factory.

Members (1)

  • methodCreateFailure
    static abstract TSelf CreateFailure(Error error)

    Creates a failed instance of `TSelf` containing the specified `error`.

    error: Error
    The error describing why the operation failed.

    Returns: A failed `TSelf` instance.

interface

IResultOutcome

Assembly: EricksonLopez.Result
public interface IResultOutcome

Defines the foundational contract for all Result outcomes. Named IResultOutcome to avoid name collision with Microsoft.AspNetCore.Http.IResult.

Members (6)

  • methodTryGetRawValue<T>
    bool TryGetRawValue<T>(out T value)

    Attempts to extract the strongly-typed underlying value of a successful generic result without boxing value-type payloads.

    value: out T
    When this method returns `true`, contains the extracted value; otherwise, the default value of `T`.

    Returns: `true` if the result is successful and carries a value compatible with `T`; otherwise, `false`.

    Type parameters: T: The target type to extract.

  • propertyError
    Error? Error { get; }

    Gets the error associated with a failed result, or `null` if successful.

  • propertyIsFailure
    bool IsFailure { get; }

    Gets a value indicating whether the operation failed.

  • propertyIsSuccess
    bool IsSuccess { get; }

    Gets a value indicating whether the operation succeeded.

  • propertyIsUninitialized
    bool IsUninitialized { get; }

    Gets a value indicating whether this result is an uninitialized default value (i.e., constructed via `default(Result)` or `default(Result<T>)` instead of through `Result.Success()` or `Result.Failure(Error)`).

    An uninitialized result is neither `IsSuccess` nor `IsFailure`. Code that receives an `IResultOutcome` should check this property when handling all possible states, particularly in middleware or endpoint filters.

  • propertyRawValue
    object? RawValue { get; }

    Gets the raw underlying value of a successful generic result, or `null` if non-generic or failed.

struct

Result

Assembly: EricksonLopez.Result
public readonly partial struct Result
Implements: IEquatable<Result>, IResultFactory<Result>, IResultOutcome

Partial declaration of `Result` providing aggregation and combination operations.

Members (80)

  • methodBind
    public Result Bind(Func<Result> bind)

    Chains another non-generic operation if this result is successful.

    bind: Func<Result>
    The operation to execute on success.

    Returns: The result of executing `bind` if this result is successful; otherwise, a failure with the original error.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodBind<TNext>
    public Result<TNext> Bind<TNext>(Func<Result<TNext>> bind)

    Chains a typed operation if this result is successful.

    bind: Func<Result<TNext>>
    The operation to execute on success.

    Returns: The result of executing `bind` if this result is successful; otherwise, a typed failure with the original error.

    Type parameters: TNext: The value type of the chained result. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodBind<TState, TNext>
    public Result<TNext> Bind<TState, TNext>(TState state, Func<TState, Result<TNext>> bind)

    Chains a typed operation using captured state if this result is successful.

    state: TState
    The state value passed to the bind function.
    bind: Func<TState, Result<TNext>>
    The operation to execute on success.

    Returns: The result of executing `bind` if this result is successful; otherwise, a typed failure with the original error.

    💡 Allocation tip: This overload accepts captured state to avoid closure allocations. Prefer this over `Bind(Func<Result<TNext>>)` when you would otherwise capture a variable from an outer scope. Type parameters: TState: The type of the state object passed to the bind function.; TNext: The value type of the chained result. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodBind<TState>
    public Result Bind<TState>(TState state, Func<TState, Result> bind)

    Chains another non-generic operation using captured state if this result is successful.

    state: TState
    The state value passed to the bind function.
    bind: Func<TState, Result>
    The operation to execute on success.

    Returns: The result of executing `bind` if this result is successful; otherwise, a failure with the original error.

    Type parameters: TState: The type of the state object passed to the bind function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodCombine
    public static Result Combine(params ReadOnlySpan<Result> results)

    Aggregates multiple results using a read-only span. Returns success if all succeed, or a compound failure containing all errors when one or more fail.

    results: params ReadOnlySpan<Result>
    The span of results to aggregate.

    Returns: A successful `Result` if all inputs succeed; otherwise, a compound failure containing all errors.

    Exceptions: InvalidOperationException: One or more results are uninitialized

  • methodCombine
    public static Result Combine(params Result[] results)

    Aggregates multiple results. Returns success if all succeed, or a compound failure containing all errors when one or more fail.

    results: params Result[]
    The array of results to aggregate.

    Returns: A successful `Result` if all inputs succeed; otherwise, a compound failure containing all errors.

    This overload accepts `params Result[]` for compatibility with C# 12 and earlier, which do not support `params ReadOnlySpan<T>`. It delegates to the `Combine(ReadOnlySpan<Result>)` overload. Exceptions: InvalidOperationException: One or more results are uninitialized

  • methodCombine<T1, T2, T3, T4, T5>
    public static Result<(T1, T2, T3, T4, T5)> Combine<T1, T2, T3, T4, T5>(in Result<T1> r1, in Result<T2> r2, in Result<T3> r3, in Result<T4> r4, in Result<T5> r5)

    Aggregates five typed results into a value tuple.

    r1: in Result<T1>
    The first result, passed by readonly reference.
    r2: in Result<T2>
    The second result, passed by readonly reference.
    r3: in Result<T3>
    The third result, passed by readonly reference.
    r4: in Result<T4>
    The fourth result, passed by readonly reference.
    r5: in Result<T5>
    The fifth result, passed by readonly reference.

    Returns: A successful `Result<TValue>` containing a tuple of values if all inputs succeed; otherwise, a compound failure containing all errors.

    Type parameters: T1: The type of the first value.; T2: The type of the second value.; T3: The type of the third value.; T4: The type of the fourth value.; T5: The type of the fifth value. Exceptions: InvalidOperationException: One or more results are uninitialized

  • methodCombine<T1, T2, T3, T4>
    public static Result<(T1, T2, T3, T4)> Combine<T1, T2, T3, T4>(in Result<T1> r1, in Result<T2> r2, in Result<T3> r3, in Result<T4> r4)

    Aggregates four typed results into a value tuple.

    r1: in Result<T1>
    The first result, passed by readonly reference.
    r2: in Result<T2>
    The second result, passed by readonly reference.
    r3: in Result<T3>
    The third result, passed by readonly reference.
    r4: in Result<T4>
    The fourth result, passed by readonly reference.

    Returns: A successful `Result<TValue>` containing a tuple of values if all inputs succeed; otherwise, a compound failure containing all errors.

    Type parameters: T1: The type of the first value.; T2: The type of the second value.; T3: The type of the third value.; T4: The type of the fourth value. Exceptions: InvalidOperationException: One or more results are uninitialized

  • methodCombine<T1, T2, T3>
    public static Result<(T1, T2, T3)> Combine<T1, T2, T3>(in Result<T1> r1, in Result<T2> r2, in Result<T3> r3)

    Aggregates three typed results into a value tuple.

    r1: in Result<T1>
    The first result, passed by readonly reference.
    r2: in Result<T2>
    The second result, passed by readonly reference.
    r3: in Result<T3>
    The third result, passed by readonly reference.

    Returns: A successful `Result<TValue>` containing a tuple of values if all inputs succeed; otherwise, a compound failure containing all errors.

    Type parameters: T1: The type of the first value.; T2: The type of the second value.; T3: The type of the third value. Exceptions: InvalidOperationException: One or more results are uninitialized

  • methodCombine<T1, T2>
    public static Result<(T1, T2)> Combine<T1, T2>(in Result<T1> r1, in Result<T2> r2)

    Aggregates two typed results into a value tuple.

    r1: in Result<T1>
    The first result, passed by readonly reference.
    r2: in Result<T2>
    The second result, passed by readonly reference.

    Returns: A successful `Result<TValue>` containing a tuple of values if all inputs succeed; otherwise, a compound failure containing all errors.

    Type parameters: T1: The type of the first value.; T2: The type of the second value. Exceptions: InvalidOperationException: One or more results are uninitialized

  • methodCombine<T>
    public static Result<IReadOnlyList<T>> Combine<T>(params ReadOnlySpan<Result<T>> results)

    Aggregates homogeneous typed results using a read-only span. Returns all values on success, or a compound failure on any error.

    results: params ReadOnlySpan<Result<T>>
    The span of typed results to aggregate.

    Returns: A successful `Result<TValue>` containing a list of all values if all inputs succeed; otherwise, a compound failure containing all errors.

    Type parameters: T: The type of the successful values. Exceptions: InvalidOperationException: One or more results are uninitialized

  • methodCombine<T>
    public static Result<IReadOnlyList<T>> Combine<T>(params Result<T>[] results)

    Aggregates homogeneous typed results. Returns all values on success, or a compound failure on any error.

    results: params Result<T>[]
    The array of typed results to aggregate.

    Returns: A successful `Result<TValue>` containing a list of all values if all inputs succeed; otherwise, a compound failure containing all errors.

    This overload accepts `params Result<T>[]` for compatibility with C# 12 and earlier, which do not support `params ReadOnlySpan<T>`. It delegates to the `Combine<T>(ReadOnlySpan<Result<T>>)` overload. Type parameters: T: The type of the successful values. Exceptions: InvalidOperationException: One or more results are uninitialized

  • methodCreateFailure
    public static Result CreateFailure(Error error)

    Creates a failed instance of `TSelf` containing the specified `error`.

    error: Error
    The error describing why the operation failed.

    Returns: A failed `TSelf` instance.

  • methodDeconstruct
    public void Deconstruct(out bool isSuccess, out Error? error)

    Deconstructs the result into its success state and optional error.

    isSuccess: out bool
    When this method returns, contains `true` if the result succeeded; otherwise, `false`.
    error: out Error?
    When this method returns, contains the associated `Error` if the result failed; otherwise, `null`.
  • methodEnsure
    public Result Ensure(Func<bool> predicate, Error error)

    Validates that the specified predicate is satisfied when this result is successful.

    predicate: Func<bool>
    The condition to test on success.
    error: Error
    The error to return if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with `error`.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure
    public Result Ensure(Func<bool> predicate, Func<Error> errorFactory)

    Validates a successful result using `predicate`, constructing the error lazily via `errorFactory` only when the predicate fails.

    predicate: Func<bool>
    The condition to test on success.
    errorFactory: Func<Error>
    A factory that generates the error if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with the generated error.

    Prefer this overload over `Ensure(Func<bool>, Error)` when error construction is expensive (e.g., captures `Activity.Current`, allocates metadata, or involves string formatting). The error factory is never invoked on the success path. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure<TState>
    public Result Ensure<TState>(TState state, Func<TState, bool> predicate, Error error)

    Validates that the specified predicate is satisfied using captured state when this result is successful.

    state: TState
    The state value passed to the predicate.
    predicate: Func<TState, bool>
    The condition to test on success.
    error: Error
    The error to return if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with `error`.

    Type parameters: TState: The type of the state object passed to the predicate. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure<TState>
    public Result Ensure<TState>(TState state, Func<TState, bool> predicate, Func<Error> errorFactory)

    Validates a successful result using `predicate` with captured state, constructing the error lazily via `errorFactory` only when the predicate fails.

    state: TState
    The state value passed to the predicate.
    predicate: Func<TState, bool>
    The condition to test on success.
    errorFactory: Func<Error>
    A factory that generates the error if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with the generated error.

    Type parameters: TState: The type of the state object passed to the predicate. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEquals
    public bool Equals(in Result other)

    Determines whether the specified `Result` is equal to the current instance.

    other: in Result
    The other result to compare against, passed by readonly reference.

    Returns: `true` if both results represent the same outcome; otherwise, `false`.

    Two results are equal when they have the same state and — on failure — the same error (using `Error.Equals(Error?)` shallow equality). The parameter is passed by reference (`in`) to avoid copying the 16-byte struct on every call; this is especially important since `operator ==` uses `in` parameters.

  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodExecute
    public void Execute(Action onSuccess, Action<Error> onFailure)

    Invokes `onSuccess` when this result is successful, or `onFailure` when it is a failure — without returning a value.

    onSuccess: Action
    Action invoked when the result is `successful`.
    onFailure: Action<Error>
    Action invoked with the `Error` when the result is a failure.

    `Execute` is the void side-effect counterpart to `Match<TOut>`: use `Match` when you need a return value, and `Execute` for pure side-effects (logging, dispatching events, updating state). Naming note: The name `Execute` is borrowed from functional programming (e.g. F# `match` expressions evaluated for side-effects). In the .NET idiom, a close equivalent would be `Visit` or `Execute`. `Execute` was chosen for conciseness and consistency with functional Result libraries; it does not refer to the C# `Execute` statement. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodExecute<TState>
    public void Execute<TState>(TState state, Action<TState> onSuccess, Action<TState, Error> onFailure)

    Invokes `onSuccess` or `onFailure` for their side-effects, forwarding `state` to avoid a closure allocation.

    state: TState
    The state object forwarded to the callbacks to avoid closure allocations.
    onSuccess: Action<TState>
    The action to invoke when the result is successful.
    onFailure: Action<TState, Error>
    The action to invoke when the result is a failure.

    Use this overload in hot paths where capturing variables in a closure would cause heap allocation. See `Execute(Action, Action<Error>)` for the naming rationale. Type parameters: TState: The type of the state argument passed to the callbacks. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodFailure
    public static Result Failure(Error error)

    Creates a new failed `Result` with the specified error.

    error: Error
    The error describing the failure.

    Returns: A failed `Result` instance containing `error`.

    Exceptions: ArgumentNullException: `error` is `null`

  • methodFailure<TValue>
    public static Result<TValue> Failure<TValue>(Error error)

    Creates a new failed `Result<TValue>` with the specified error.

    error: Error
    The error describing the failure.

    Returns: A failed `Result<TValue>` instance containing `error`.

    Type parameters: TValue: The type of the expected successful value. Exceptions: ArgumentNullException: `error` is `null`

  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodInspect
    public Result Inspect(Action<Result> action)

    Executes `action` unconditionally with the current result (success or failure), then returns this result unchanged. Useful for logging, debugging, or auditing the pipeline at any point.

    action: Action<Result>
    The action to execute with the current result.

    Returns: The current result instance unchanged.

    Inspect vs TapOnSuccess: **Method**: When it runs / What it receives - **`Inspect(Action<Result>)`**: Always (success or failure). Receives the full `Result`. - **`TapOnSuccess(Action)`**: Only when the result is a success. Receives nothing. - **`TapOnFailure(Action<Error>)`**: Only when the result is a failure. Receives the `Error`. Use `Inspect(Action<Result>)` when you need to observe any outcome (e.g., structured logging that records both success and failure in a single callback). Use `TapOnSuccess(Action)` when you only care about the success path and do not need access to the `Result` wrapper. Exceptions: InvalidOperationException: The result is an uninitialized default value Example:

    // Log every outcome (success + failure) without branching:
    result
        .Inspect(r => logger.LogInformation("Pipeline step completed. IsSuccess={IsSuccess}", r.IsSuccess))
        .TapOnFailure(err => logger.LogError("Failure detail: {Code}", err.Code));
  • methodInspect<TState>
    public Result Inspect<TState>(TState state, Action<TState, Result> action)

    Executes `action` unconditionally with captured `state` and the current result, then returns this result unchanged.

    state: TState
    The state value passed to the action.
    action: Action<TState, Result>
    The action to execute with state and result.

    Returns: The current result instance unchanged.

    💡 Allocation tip: This overload passes context via `state` instead of a captured closure. See `Inspect(Action<Result>)` for the distinction between `Inspect` and `TapOnSuccess`. Type parameters: TState: The type of the state object passed to the action. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMap<TNext>
    public Result<TNext> Map<TNext>(Func<TNext> mapper)

    Projects a successful Result into a `Result<TNext>` by executing `mapper` on success. If the Result is a failure, returns `Result.Failure<TNext>` with the existing error.

    mapper: Func<TNext>
    A function that produces the value for the success case.

    Returns: A `Result<TNext>` with the mapped value on success, or the original error on failure.

    💡 Allocation tip: If `mapper` captures variables from an outer scope (closure), prefer the `Map<TState, TNext>(TState, Func<TState, TNext>)` overload to pass context without allocating a closure object on the heap. Type parameters: TNext: The output value type. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMap<TState, TNext>
    public Result<TNext> Map<TState, TNext>(TState state, Func<TState, TNext> mapper)

    Projects a successful Result into a `Result<TNext>` using a state argument to avoid closure allocations.

    state: TState
    An external value passed to `mapper` to avoid a closure.
    mapper: Func<TState, TNext>
    A function that receives the state and produces the result value.

    Returns: A `Result<TNext>` with the mapped value on success, or the original error on failure.

    Type parameters: TState: The type of the state argument passed to `mapper`.; TNext: The output value type. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMapError
    public Result MapError(Func<Error, Error> mapper)

    Transforms the error of a failed result using the provided `mapper`. Returns the same success result unchanged.

    mapper: Func<Error, Error>
    The function used to map the error if this result is a failure.

    Returns: A new failed result with the transformed error, or the current success result unchanged.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMapError<TState>
    public Result MapError<TState>(TState state, Func<TState, Error, Error> mapper)

    Transforms the error of a failed result using the provided `mapper` and captured state. Returns the same success result unchanged.

    state: TState
    The state value passed to the mapper function.
    mapper: Func<TState, Error, Error>
    The function used to map the error if this result is a failure.

    Returns: A new failed result with the transformed error, or the current success result unchanged.

    Type parameters: TState: The type of the state object passed to the mapper function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMapFailure<TOut>
    public TOut MapFailure<TOut>(Func<Error, TOut> onFailure, TOut successDefault)

    Maps a failure `Error` to a value of type `TOut`, or returns `successDefault` when this result is successful.

    onFailure: Func<Error, TOut>
    A function that produces a `TOut` from the `Error`.
    successDefault: TOut
    The value to return when the result is successful.

    Returns: The result of invoking `onFailure` on failure, or `successDefault` on success.

    Use this when you only need to handle the failure branch. For transforming both branches, use `Match<TOut>(Func<TOut>, Func<Error, TOut>)`. 💡 Allocation tip: If `onFailure` captures variables from an outer scope, use `MapFailure<TState, TOut>(TState, Func<TState, Error, TOut>, TOut)` to pass the captured values as a `TState` parameter and avoid closure allocation. Type parameters: TOut: The output type of the transformation. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMapFailure<TState, TOut>
    public TOut MapFailure<TState, TOut>(TState state, Func<TState, Error, TOut> onFailure, TOut successDefault)

    Maps a failure `Error` to a value of type `TOut` using captured `state` to avoid closure allocation. Returns `successDefault` when this result is successful.

    state: TState
    An external value passed to `onFailure` to avoid capturing it in a closure.
    onFailure: Func<TState, Error, TOut>
    A function that maps the captured state and the `Error` to a `TOut` value.
    successDefault: TOut
    The value to return when the result is successful.

    Returns: The result of invoking `onFailure` with `state` and the error on failure, or `successDefault` on success.

    Type parameters: TState: The type of the state argument passed to `onFailure`.; TOut: The output type produced by the failure mapping function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMatch<TOut>
    public TOut Match<TOut>(Func<TOut> onSuccess, Func<Error, TOut> onFailure)

    Evaluates the corresponding branch depending on whether the result is a success or failure.

    onSuccess: Func<TOut>
    The function to evaluate if the result is successful.
    onFailure: Func<Error, TOut>
    The function to evaluate with the `Error` if the result is a failure.

    Returns: The value produced by either `onSuccess` or `onFailure`.

    Type parameters: TOut: The output type produced by the matching functions. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMatch<TState, TOut>
    public TOut Match<TState, TOut>(TState state, Func<TState, TOut> onSuccess, Func<TState, Error, TOut> onFailure)

    Evaluates the corresponding branch using captured state to avoid closure allocations.

    state: TState
    The state value passed to the matching delegates.
    onSuccess: Func<TState, TOut>
    The function to evaluate if the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function to evaluate with the state and `Error` if the result is a failure.

    Returns: The value produced by either `onSuccess` or `onFailure`.

    Type parameters: TState: The type of the state object passed to the matching functions.; TOut: The output type produced by the matching functions. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMerge<T>
    public static Result<T> Merge<T>(in Result guard, in Result<T> next)

    Merges a guard non-generic result with a typed result, returning the typed result if the guard succeeds.

    guard: in Result
    The guard result to check first, passed by readonly reference.
    next: in Result<T>
    The typed result to return if the guard succeeds, passed by readonly reference.

    Returns: The failure from `guard` if it failed; otherwise, `next`.

    Type parameters: T: The value type of the typed result. Exceptions: InvalidOperationException: `guard` or `next` is uninitialized

  • methodRecover
    public Result Recover(Func<Error, Result> recovery)

    If this result is a failure, invokes `recovery` to attempt a corrective result.

    recovery: Func<Error, Result>
    The recovery function producing a corrective result from the failure `Error`.

    Returns: The recovery result if this instance is a failure; otherwise, this instance unchanged.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodRecover<TState>
    public Result Recover<TState>(TState state, Func<TState, Error, Result> recovery)

    If this result is a failure, invokes `recovery` with captured state to attempt a corrective result.

    state: TState
    The state value passed to the recovery function.
    recovery: Func<TState, Error, Result>
    The recovery function producing a corrective result from state and the failure `Error`.

    Returns: The recovery result if this instance is a failure; otherwise, this instance unchanged.

    Type parameters: TState: The type of the state object passed to the recovery function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodSuccess
    public static Result Success()

    Creates a new successful `Result`.

    Returns: A successful `Result` instance.

  • methodSuccess<TValue>
    public static Result<TValue> Success<TValue>(TValue value)

    Creates a new successful `Result<TValue>` wrapping the specified value.

    value: TValue
    The value to wrap.

    Returns: A successful `Result<TValue>` instance containing `value`.

    Type parameters: TValue: The type of the successful value.

  • methodTap
    public Result Tap(Action onSuccess)

    Executes `onSuccess` if this result is successful, then returns this result unchanged.

    onSuccess: Action
    The action to execute if the result is successful.

    Returns: The current result instance unchanged.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTap<TState>
    public Result Tap<TState>(TState state, Action<TState> onSuccess)

    Executes `onSuccess` with captured state if this result is successful, then returns this result unchanged.

    state: TState
    The state value passed to the action.
    onSuccess: Action<TState>
    The action to execute if the result is successful.

    Returns: The current result instance unchanged.

    Type parameters: TState: The type of the state object passed to the action. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTapOnFailure
    public Result TapOnFailure(Action<Error> onFailure)

    Executes `onFailure` if this result is a failure, then returns this result unchanged.

    onFailure: Action<Error>
    The action to execute with the `Error` if the result is a failure.

    Returns: The current result instance unchanged.

    Executes the action only on failure; symmetric with `TapOnSuccess(Action)`. Use `Inspect(Action<Result>)` if you need unconditional execution (both success and failure). 💡 Allocation tip: Use `TapOnFailure<TState>(TState, Action<TState, Error>)` to avoid closure allocations when capturing outer variables. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTapOnFailure<TState>
    public Result TapOnFailure<TState>(TState state, Action<TState, Error> onFailure)

    Executes `onFailure` with captured state if this result is a failure, then returns this result unchanged.

    state: TState
    The state value passed to the action.
    onFailure: Action<TState, Error>
    The action to execute with state and error if the result is a failure.

    Returns: The current result instance unchanged.

    💡 Allocation tip: This overload passes context via `state` instead of a captured closure. Type parameters: TState: The type of the state object passed to the action. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTapOnSuccess
    public Result TapOnSuccess(Action onSuccess)

    Executes `onSuccess` if this result is successful, then returns this result unchanged.

    onSuccess: Action
    The action to execute if the result is successful.

    Returns: The current result instance unchanged.

    Executes the action only on success; symmetric with `TapOnFailure(Action<Error>)`. Use `Inspect(Action<Result>)` if you need unconditional execution (both success and failure). 💡 Allocation tip: Use `TapOnSuccess<TState>(TState, Action<TState>)` to avoid closure allocations when capturing outer variables. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTapOnSuccess<TState>
    public Result TapOnSuccess<TState>(TState state, Action<TState> onSuccess)

    Executes `onSuccess` with captured state if this result is successful, then returns this result unchanged.

    state: TState
    The state value passed to the action.
    onSuccess: Action<TState>
    The action to execute if the result is successful.

    Returns: The current result instance unchanged.

    💡 Allocation tip: This overload passes context via `state` instead of a captured closure. Type parameters: TState: The type of the state object passed to the action. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTry
    public static Result Try(Action action, Func<Exception, Error> errorHandler)

    Executes `action` and wraps any non-fatal exception into a failure result.

    action: Action
    The action to execute.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.

    Returns: Success if `action` completes without throwing; otherwise a failure result.

    OperationCanceledException handling: `OperationCanceledException` (including `TaskCanceledException`) is caught and converted into a `Result.Failure` via `errorHandler`. This is intentional: cancellation is normal async control flow, and the caller may want to return a specific error (e.g., `Error.Unavailable("Op.Cancelled", "The operation was cancelled.")`). If you need to propagate cancellation as an exception instead of a failure result, use a `when` filter on the `errorHandler` to re-throw:

    Result.Try(
        () => DoWork(),
        ex => ex is OperationCanceledException oce
            ? throw oce  // re-propagates cancellation
            : Error.Failure("Op.Failed", ex.Message));

    Fatal exceptions (`OutOfMemoryException`, `StackOverflowException`, `AccessViolationException`) are never caught and always propagate.

  • methodTry<T>
    public static Result<T> Try<T>(Func<T> func, Func<Exception, Error> errorHandler)

    Executes the specified function and wraps any non-fatal exception into a typed failure result.

    func: Func<T>
    The synchronous function to execute.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.

    Returns: A successful `Result<T>` containing the returned value, or a failure result if an exception occurs.

    Type parameters: T: The return value type of the function.

  • methodTry<TState, T>
    public static Result<T> Try<TState, T>(TState state, Func<T> func, Func<TState, Exception, Error> errorHandler)

    Executes `func` and wraps any non-fatal exception into a failure result, forwarding `state` to the error handler to avoid a closure allocation.

    state: TState
    An external value passed to `errorHandler` to avoid capturing it in a closure.
    func: Func<T>
    The synchronous function to execute.
    errorHandler: Func<TState, Exception, Error>
    Maps the caught exception and state to an `Error`.

    Returns: A successful `Result<T>` containing the returned value, or a failure result if an exception occurs.

    💡 Allocation tip: Use this overload when `errorHandler` would otherwise capture a variable from an outer scope (causing a closure allocation). Type parameters: TState: The type of the state argument passed to `errorHandler`.; T: The success value type.

  • methodTry<TState>
    public static Result Try<TState>(TState state, Action action, Func<TState, Exception, Error> errorHandler)

    Executes `action` and wraps any non-fatal exception into a failure result, forwarding `state` to the error handler to avoid a closure allocation.

    state: TState
    An external value passed to `errorHandler` to avoid capturing it in a closure.
    action: Action
    The synchronous action to execute.
    errorHandler: Func<TState, Exception, Error>
    Maps the caught exception and state to an `Error`.

    Returns: Success if `action` completes without throwing; otherwise a failure result.

    💡 Allocation tip: Use this overload when `errorHandler` would otherwise capture a variable from an outer scope (causing a closure allocation). For example:

    var operationName = "SaveOrder";
    // Without TState: errorHandler captures operationName — heap allocation
    var result = Result.Try(() => DoWork(), ex => Error.Failure($"{operationName}.Failed", ex.Message));
    
    // With TState: no closure — zero heap allocation for the handler
    var result = Result.Try(operationName, () => DoWork(), (state, ex) => Error.Failure($"{state}.Failed", ex.Message));

    Type parameters: TState: The type of the state argument passed to `errorHandler`.

  • methodTryAsync
    public static async Task<Result> TryAsync(Func<CancellationToken, Task> action, Func<Exception, Error> errorHandler, CancellationToken cancellationToken = default)

    Executes an async action with cancellation support, wrapping exceptions into a failure result.

    action: Func<CancellationToken, Task>
    The async action to execute accepting a cancellation token.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a successful or failure result.

  • methodTryAsync
    public static async Task<Result> TryAsync(Func<Task> action, Func<Exception, Error> errorHandler)

    Executes an async `action` and wraps any non-fatal exception into a failure result.

    action: Func<Task>
    The async action to execute.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.

    Returns: Success if `action` completes without throwing; otherwise a failure result.

    OperationCanceledException handling: `OperationCanceledException` is caught and converted into a failure via `errorHandler`. To re-propagate cancellation instead, check for `OperationCanceledException` in `errorHandler` and re-throw it. See `Try(Action, Func<Exception, Error>)` for a code example.

  • methodTryAsync<T>
    public static async Task<Result<T>> TryAsync<T>(Func<CancellationToken, Task<T>> func, Func<Exception, Error> errorHandler, CancellationToken cancellationToken = default)

    Executes an async function with cancellation support, wrapping exceptions into a failure result.

    func: Func<CancellationToken, Task<T>>
    The asynchronous function accepting a cancellation token.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a successful `Result<T>` or a failure result.

    Type parameters: T: The return value type of the asynchronous operation.

  • methodTryAsync<T>
    public static async Task<Result<T>> TryAsync<T>(Func<Task<T>> func, Func<Exception, Error> errorHandler)

    Executes the specified asynchronous function and wraps any non-fatal exception into a typed failure result.

    func: Func<Task<T>>
    The asynchronous function to execute.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.

    Returns: A task representing the asynchronous operation. The task result contains a successful `Result<T>` or a failure result.

    Type parameters: T: The return value type of the asynchronous operation.

  • methodTryAsyncValue
    public static async ValueTask<Result> TryAsyncValue(Func<CancellationToken, ValueTask> action, Func<Exception, Error> errorHandler, CancellationToken cancellationToken = default)

    Executes an async action returning `ValueTask` with cancellation support, wrapping any non-fatal exception into a `ValueTask<Result>`.

    action: Func<CancellationToken, ValueTask>
    The async action to execute accepting a cancellation token.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A `ValueTask<TResult>` whose result is a successful `Result` if `action` completes without throwing; otherwise a failure result.

  • methodTryAsyncValue
    public static async ValueTask<Result> TryAsyncValue(Func<ValueTask> action, Func<Exception, Error> errorHandler)

    Executes an async action returning `ValueTask`, wrapping any non-fatal exception into a `ValueTask<Result>`.

    action: Func<ValueTask>
    The async action to execute.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.

    Returns: A `ValueTask<TResult>` whose result is a successful `Result` if `action` completes without throwing; otherwise a failure result.

    Prefer this overload over the `Task<Result>` variant when composing end-to-end `ValueTask` pipelines to avoid unnecessary `Task` state machine allocation.

  • methodTryAsyncValue<T>
    public static async ValueTask<Result<T>> TryAsyncValue<T>(Func<CancellationToken, ValueTask<T>> func, Func<Exception, Error> errorHandler, CancellationToken cancellationToken = default)

    Executes an async function returning `ValueTask<T>` with cancellation support, wrapping any non-fatal exception into a `ValueTask<Result<T>>`.

    func: Func<CancellationToken, ValueTask<T>>
    The asynchronous function accepting a cancellation token.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A `ValueTask<TResult>` whose result is a successful `Result<T>` containing the returned value, or a failure result if an exception occurs.

    Type parameters: T: The value type of the result.

  • methodTryAsyncValue<T>
    public static async ValueTask<Result<T>> TryAsyncValue<T>(Func<ValueTask<T>> func, Func<Exception, Error> errorHandler)

    Executes an async function returning `ValueTask<T>`, wrapping any non-fatal exception into a `ValueTask<Result<T>>`.

    func: Func<ValueTask<T>>
    The asynchronous function to execute.
    errorHandler: Func<Exception, Error>
    Maps a caught exception to an `Error`.

    Returns: A `ValueTask<TResult>` whose result is a successful `Result<T>` containing the returned value, or a failure result if an exception occurs.

    Prefer this overload over the `Task<Result<T>>` variant when composing end-to-end `ValueTask` pipelines. Type parameters: T: The value type of the result.

  • methodTryAsyncValue<TState, T>
    public static async ValueTask<Result<T>> TryAsyncValue<TState, T>(TState state, Func<CancellationToken, ValueTask<T>> func, Func<TState, Exception, Error> errorHandler, CancellationToken cancellationToken = default)

    Executes an async function returning `ValueTask<T>` with cancellation support, wrapping any non-fatal exception into a `ValueTask<Result<T>>`, forwarding `state` to the error handler to avoid a closure allocation.

    state: TState
    An external value passed to `errorHandler` to avoid capturing it in a closure.
    func: Func<CancellationToken, ValueTask<T>>
    The asynchronous function accepting a cancellation token.
    errorHandler: Func<TState, Exception, Error>
    Maps the caught exception and state to an `Error`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A `ValueTask<TResult>` whose result is a successful `Result<T>` containing the returned value, or a failure result if an exception occurs.

    Type parameters: TState: The type of the state argument passed to `errorHandler`.; T: The value type of the result.

  • methodTryAsyncValue<TState, T>
    public static async ValueTask<Result<T>> TryAsyncValue<TState, T>(TState state, Func<ValueTask<T>> func, Func<TState, Exception, Error> errorHandler)

    Executes an async function returning `ValueTask<T>`, wrapping any non-fatal exception into a `ValueTask<Result<T>>`, forwarding `state` to the error handler to avoid a closure allocation.

    state: TState
    An external value passed to `errorHandler` to avoid capturing it in a closure.
    func: Func<ValueTask<T>>
    The asynchronous function to execute.
    errorHandler: Func<TState, Exception, Error>
    Maps the caught exception and state to an `Error`.

    Returns: A `ValueTask<TResult>` whose result is a successful `Result<T>` containing the returned value, or a failure result if an exception occurs.

    Type parameters: TState: The type of the state argument passed to `errorHandler`.; T: The value type of the result.

  • methodTryGetError
    public bool TryGetError(out Error error)

    Attempts to get the error if this result is a failure. Returns `false` for both `IsSuccess` and uninitialized default results.

    error: out Error
    The error, or `null` if the result is not a failure.

    Returns: `true` if this result is a failure and `error` has been set; `false` for both successful results and uninitialized default results.

    ⚠ Uninitialized results: This overload returns `false` silently for `default(Result)` without indicating that the result is in an invalid state. If you need to distinguish between Success and Uninitialized, use `TryGetError(out Error, out bool)` which provides an `isUninitialized` output. Always construct results via `Success()` or `Failure(Error)`.

  • methodTryGetError
    public bool TryGetError(out Error error, out bool isUninitialized)

    Attempts to retrieve the error, distinguishing between failure and uninitialized states.

    error: out Error
    When this method returns, contains the associated `Error` if the result is a failure; otherwise, `null`.
    isUninitialized: out bool
    When this method returns, contains `true` if the result is an uninitialized default value; otherwise, `false`.

    Returns: `true` if the result is a failure and `error` is populated; otherwise, `false`.

  • methodValidateAll
    public static Result ValidateAll(params ReadOnlySpan<Func<Result>> validators)

    Executes all provided validation functions and accumulates any errors. Returns `Success()` if all validators succeed, or a compound failure containing all encountered errors if one or more validators fail.

    validators: params ReadOnlySpan<Func<Result>>
    The validation functions to execute.

    Returns: A successful Result if all validations pass; otherwise, a Failure containing all accumulated validation errors.

    Exceptions: InvalidOperationException: One or more validated results are uninitialized

  • methodValidateAll<T>
    public static Result<T> ValidateAll<T>(T value, params ReadOnlySpan<Func<T, Result>> validators)

    Executes all validation functions against `value` and accumulates any errors. Returns `Success<T>(T)` with `value` if all validators pass, or a compound failure containing all encountered errors if one or more fail.

    value: T
    The target value to validate.
    validators: params ReadOnlySpan<Func<T, Result>>
    The validation functions to execute.

    Returns: A successful `Result<T>` containing `value` if all pass; otherwise, a failure.

    Type parameters: T: The type of the validated value. Exceptions: ArgumentNullException: One or more validator delegates in `validators` is `null`; InvalidOperationException: One or more validated results are uninitialized

  • methodValidateAllAsync
    public static async Task<Result> ValidateAllAsync(IReadOnlyList<Func<CancellationToken, Task<Result>>> validators, CancellationToken cancellationToken = default)

    Asynchronously executes all validation functions sequentially and accumulates any errors.

    validators: IReadOnlyList<Func<CancellationToken, Task<Result>>>
    The collection of asynchronous validation functions to execute sequentially.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operations.

    Returns: A task representing the asynchronous operation. The task result contains a successful `Result` if all validations pass, or a compound failure if one or more fail.

    Validators run sequentially in the order provided. For concurrent/parallel validation of multiple I/O-bound tasks, use `ValidateAllParallelAsync(IReadOnlyList<Func<CancellationToken, Task<Result>>>, CancellationToken)`. Exceptions: ArgumentNullException: `validators` or any validator element is `null`; OperationCanceledException: The operation was canceled; InvalidOperationException: One or more validated results are uninitialized

  • methodValidateAllAsync
    public static async ValueTask<Result> ValidateAllAsync(IReadOnlyList<Func<CancellationToken, ValueTask<Result>>> validators, CancellationToken cancellationToken = default)

    Asynchronously executes all validation functions returning `ValueTask<Result>` and accumulates any errors.

    validators: IReadOnlyList<Func<CancellationToken, ValueTask<Result>>>
    The collection of asynchronous validation functions to execute.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operations.

    Returns: A value task representing the asynchronous operation. The task result contains a successful `Result` if all validations pass, or a compound failure if one or more fail.

    Exceptions: ArgumentNullException: `validators` or any validator element is `null`; OperationCanceledException: The operation was canceled; InvalidOperationException: One or more validated results are uninitialized

  • methodValidateAllAsync<T>
    public static async Task<Result<T>> ValidateAllAsync<T>(T value, IReadOnlyList<Func<T, CancellationToken, Task<Result>>> validators, CancellationToken cancellationToken = default)

    Asynchronously executes all validation functions against the specified value and accumulates any errors.

    value: T
    The target value to validate.
    validators: IReadOnlyList<Func<T, CancellationToken, Task<Result>>>
    The collection of asynchronous validation functions to execute.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operations.

    Returns: A task representing the asynchronous operation. The task result contains a successful `Result<T>` containing `value` if all pass, or a compound failure if one or more fail.

    Type parameters: T: The type of the validated value. Exceptions: ArgumentNullException: `validators` or any validator element is `null`; OperationCanceledException: The operation was canceled; InvalidOperationException: One or more validated results are uninitialized

  • methodValidateAllAsync<T>
    public static async ValueTask<Result<T>> ValidateAllAsync<T>(T value, IReadOnlyList<Func<T, CancellationToken, ValueTask<Result>>> validators, CancellationToken cancellationToken = default)

    Asynchronously executes all validation functions against the specified value returning `ValueTask<Result>` and accumulates any errors.

    value: T
    The target value to validate.
    validators: IReadOnlyList<Func<T, CancellationToken, ValueTask<Result>>>
    The collection of asynchronous validation functions to execute.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operations.

    Returns: A value task representing the asynchronous operation. The task result contains a successful `Result<T>` containing `value` if all pass, or a compound failure if one or more fail.

    Type parameters: T: The type of the validated value. Exceptions: ArgumentNullException: `validators` or any validator element is `null`; OperationCanceledException: The operation was canceled; InvalidOperationException: One or more validated results are uninitialized

  • methodValidateAllParallelAsync
    public static async Task<Result> ValidateAllParallelAsync(IReadOnlyList<Func<CancellationToken, Task<Result>>> validators, CancellationToken cancellationToken = default)

    Concurrently executes all validation functions in parallel and accumulates any errors. Returns `Success()` if all validators succeed, or a compound failure containing all encountered errors if one or more validators fail.

    validators: IReadOnlyList<Func<CancellationToken, Task<Result>>>
    The collection of asynchronous validation functions to execute concurrently.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operations.

    Returns: A task representing the asynchronous operation with accumulated validation results.

    Exceptions: ArgumentNullException: `validators` or any validator element is `null`; OperationCanceledException: The operation was canceled; InvalidOperationException: One or more validated results are uninitialized

  • methodValidateAllParallelAsync<T>
    public static async Task<Result<T>> ValidateAllParallelAsync<T>(T value, IReadOnlyList<Func<T, CancellationToken, Task<Result>>> validators, CancellationToken cancellationToken = default)

    Concurrently executes all validation functions in parallel against the specified value and accumulates any errors.

    value: T
    The target value to validate.
    validators: IReadOnlyList<Func<T, CancellationToken, Task<Result>>>
    The collection of asynchronous validation functions to execute concurrently.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operations.

    Returns: A task representing the asynchronous operation with accumulated validation results.

    Type parameters: T: The type of the validated value. Exceptions: ArgumentNullException: `validators`, any validator element, or any returned task is `null`; OperationCanceledException: The operation was canceled; InvalidOperationException: One or more validated results are uninitialized

  • methodimplicit operator Result
    public static implicit operator Result(Error error)

    Converts an `Error` implicitly into a failed `Result`.

    error: Error
    The error to wrap in a failed result.
  • methodoperator !=
    public static bool operator !=(in Result left, in Result right)

    Determines whether two `Result` instances are not equal.

    left: in Result
    The first result to compare.
    right: in Result
    The second result to compare.

    Returns: `true` if the instances are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(in Result left, in Result right)

    Determines whether two `Result` instances are equal.

    left: in Result
    The first result to compare.
    right: in Result
    The second result to compare.

    Returns: `true` if both instances are equal; otherwise, `false`.

  • methodoperator false
    public static bool operator false(Result result)

    Evaluates whether the specified result is a failure in a boolean condition.

    result: Result
    The result to evaluate.

    Returns: `true` if the result is a failure; otherwise, `false`.

    ⚠ Uninitialized gotcha: A `default``(Result)` (state = Uninitialized) returns `false` here — the same as `IsFailure`, because `IsFailure` checks `_state == ResultState.Failure`, which evaluates to `false` for the Uninitialized state (byte value 0). An uninitialized result is neither success nor failure in boolean context: both `operator true` and `operator false` return `false`. Prefer using `IsSuccess` and `IsFailure` properties with explicit checks, or use `Match<TOut>(Func<TOut>, Func<Error, TOut>)` which throws an `InvalidOperationException` for Uninitialized results.

  • methodoperator true
    public static bool operator true(Result result)

    Evaluates whether the specified result is a success in a boolean condition.

    result: Result
    The result to evaluate.

    Returns: `true` if the result is successful; otherwise, `false`.

    ⚠ Uninitialized gotcha: A `default``(Result)` (state = Uninitialized) returns `false` here — it does NOT throw. This means an uninitialized `Result` silently evaluates as failure in `if(result)` without any diagnostic. Always construct `Result` via `Success()` or `Failure(Error)`.

  • propertyError
    public Error Error { get; }

    Gets the error associated with a failed result, or `WellKnownErrors.UninitializedError` if uninitialized.

    If the result is an uninitialized `default``(Result)`, this property returns the sentinel `WellKnownErrors.UninitializedError` rather than throwing an exception. Exceptions: InvalidOperationException: The result is in the `Success` state (`IsSuccess` is `true`).

  • propertyIsFailure
    public bool IsFailure { get; }

    Gets a value indicating whether the operation failed.

    ⚠ Uninitialized default: Returns `false` for an uninitialized `default(Result)` — the same as a success (neither `true` nor `false` corresponds to the uninitialized state). Use `IsUninitialized` to distinguish.

  • propertyIsSuccess
    public bool IsSuccess { get; }

    Gets a value indicating whether the operation succeeded.

    ⚠ Uninitialized default: Returns `false` for an uninitialized `default(Result)` — the same as a failure, but without an error. Always construct results via `Success()` or `Failure(Error)`. Use `IsUninitialized` to detect an uninitialized default explicitly.

  • propertyIsUninitialized
    public bool IsUninitialized { get; }

    Gets a value indicating whether the struct is an uninitialized default value.

class

ResultExtensions

Assembly: EricksonLopez.Result
public static partial class ResultExtensions

Async extension methods for composing `Result` and `Result<T>` pipelines over `ValueTask`.

Members (140)

  • methodBind
    public static Task<Result> Bind(this Task<Result> resultTask, Func<CancellationToken, Task<Result>> bind, CancellationToken cancellationToken = default)

    If the `Result` is a success, invokes the async `bind` delegate with a `CancellationToken`, returning its result. If the Result is a failure, returns the failure without invoking `bind`.

    resultTask: this Task<Result>
    The task containing the source result.
    bind: Func<CancellationToken, Task<Result>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the result of the binding operation.

  • methodBind
    public static Task<Result> Bind(this Task<Result> resultTask, Func<Result> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result>
    The task containing the source result.
    bind: Func<Result>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the result of the binding operation.

  • methodBind
    public static Task<Result> Bind(this Task<Result> resultTask, Func<Task<Result>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result>
    The task containing the source result.
    bind: Func<Task<Result>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the result of the binding operation.

  • methodBind
    public static ValueTask<Result> Bind(this ValueTask<Result> resultTask, Func<CancellationToken, ValueTask<Result>> bind, CancellationToken cancellationToken = default)

    If the `Result` is a success, invokes the async `bind` delegate with a `CancellationToken`, returning its result. If the Result is a failure, returns the failure without invoking `bind`.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    bind: Func<CancellationToken, ValueTask<Result>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the result of the binding operation.

  • methodBind
    public static ValueTask<Result> Bind(this ValueTask<Result> resultTask, Func<Result> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    bind: Func<Result>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the result of the binding operation.

  • methodBind
    public static ValueTask<Result> Bind(this ValueTask<Result> resultTask, Func<ValueTask<Result>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    bind: Func<ValueTask<Result>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the result of the binding operation.

  • methodBind<T, TNext>
    public static Task<Result<TNext>> Bind<T, TNext>(this Task<Result<T>> resultTask, Func<T, Result<TNext>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    bind: Func<T, Result<TNext>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: T: The type of the source result value.; TNext: The type of the transformed value.

  • methodBind<T, TNext>
    public static Task<Result<TNext>> Bind<T, TNext>(this Task<Result<T>> resultTask, Func<T, Task<Result<TNext>>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    bind: Func<T, Task<Result<TNext>>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: T: The type of the source result value.; TNext: The type of the transformed value.

  • methodBind<T, TNext>
    public static ValueTask<Result<TNext>> Bind<T, TNext>(this ValueTask<Result<T>> resultTask, Func<T, Result<TNext>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    bind: Func<T, Result<TNext>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: T: The type of the source result value.; TNext: The type of the transformed value.

  • methodBind<T, TNext>
    public static ValueTask<Result<TNext>> Bind<T, TNext>(this ValueTask<Result<T>> resultTask, Func<T, ValueTask<Result<TNext>>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    bind: Func<T, ValueTask<Result<TNext>>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: T: The type of the source result value.; TNext: The type of the transformed value.

  • methodBind<T>
    public static Task<Result> Bind<T>(this Task<Result<T>> resultTask, Func<T, Result> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    bind: Func<T, Result>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the result of the binding operation.

    Type parameters: T: The type of the source result value.

  • methodBind<T>
    public static Task<Result> Bind<T>(this Task<Result<T>> resultTask, Func<T, Task<Result>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    bind: Func<T, Task<Result>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the result of the binding operation.

    Type parameters: T: The type of the source result value.

  • methodBind<T>
    public static ValueTask<Result> Bind<T>(this ValueTask<Result<T>> resultTask, Func<T, Result> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    bind: Func<T, Result>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the result of the binding operation.

    Type parameters: T: The type of the source result value.

  • methodBind<T>
    public static ValueTask<Result> Bind<T>(this ValueTask<Result<T>> resultTask, Func<T, ValueTask<Result>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    bind: Func<T, ValueTask<Result>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the result of the binding operation.

    Type parameters: T: The type of the source result value.

  • methodBind<TNext>
    public static Task<Result<TNext>> Bind<TNext>(this Task<Result> resultTask, Func<CancellationToken, Task<Result<TNext>>> bind, CancellationToken cancellationToken = default)

    If the `Result` is a success, invokes the async `bind` delegate with a `CancellationToken`, returning a typed Result. If the Result is a failure, returns the failure without invoking `bind`.

    resultTask: this Task<Result>
    The task containing the source result.
    bind: Func<CancellationToken, Task<Result<TNext>>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodBind<TNext>
    public static Task<Result<TNext>> Bind<TNext>(this Task<Result> resultTask, Func<Result<TNext>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result>
    The task containing the source result.
    bind: Func<Result<TNext>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodBind<TNext>
    public static Task<Result<TNext>> Bind<TNext>(this Task<Result> resultTask, Func<Task<Result<TNext>>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result>
    The task containing the source result.
    bind: Func<Task<Result<TNext>>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodBind<TNext>
    public static ValueTask<Result<TNext>> Bind<TNext>(this ValueTask<Result> resultTask, Func<CancellationToken, ValueTask<Result<TNext>>> bind, CancellationToken cancellationToken = default)

    If the `Result` is a success, invokes the async `bind` delegate with a `CancellationToken`, returning a typed Result. If the Result is a failure, returns the failure without invoking `bind`.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    bind: Func<CancellationToken, ValueTask<Result<TNext>>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodBind<TNext>
    public static ValueTask<Result<TNext>> Bind<TNext>(this ValueTask<Result> resultTask, Func<Result<TNext>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    bind: Func<Result<TNext>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodBind<TNext>
    public static ValueTask<Result<TNext>> Bind<TNext>(this ValueTask<Result> resultTask, Func<ValueTask<Result<TNext>>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    bind: Func<ValueTask<Result<TNext>>>
    The binding function applied to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodBind<TState, T, TNext>
    public static Task<Result<TNext>> Bind<TState, T, TNext>(this Task<Result<T>> resultTask, TState state, Func<TState, T, Result<TNext>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    bind: Func<TState, T, Result<TNext>>
    The binding function applied to the state and result to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TNext: The type of the transformed value.

  • methodBind<TState, T, TNext>
    public static ValueTask<Result<TNext>> Bind<TState, T, TNext>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, T, Result<TNext>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    bind: Func<TState, T, Result<TNext>>
    The binding function applied to the state and result to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TNext: The type of the transformed value.

  • methodBind<TState, T>
    public static Task<Result> Bind<TState, T>(this Task<Result<T>> resultTask, TState state, Func<TState, T, Result> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    bind: Func<TState, T, Result>
    The binding function applied to the state and result to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the result of the binding operation.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodBind<TState, T>
    public static ValueTask<Result> Bind<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, T, Result> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    bind: Func<TState, T, Result>
    The binding function applied to the state and result to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the result of the binding operation.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodBind<TState, TNext>
    public static Task<Result<TNext>> Bind<TState, TNext>(this Task<Result> resultTask, TState state, Func<TState, Result<TNext>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    bind: Func<TState, Result<TNext>>
    The binding function applied to the state and result to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TNext: The type of the transformed value.

  • methodBind<TState, TNext>
    public static ValueTask<Result<TNext>> Bind<TState, TNext>(this ValueTask<Result> resultTask, TState state, Func<TState, Result<TNext>> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    bind: Func<TState, Result<TNext>>
    The binding function applied to the state and result to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the bound `Result<TNext>` on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TNext: The type of the transformed value.

  • methodBind<TState>
    public static Task<Result> Bind<TState>(this Task<Result> resultTask, TState state, Func<TState, Result> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    bind: Func<TState, Result>
    The binding function applied to the state and result to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the result of the binding operation.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodBind<TState>
    public static ValueTask<Result> Bind<TState>(this ValueTask<Result> resultTask, TState state, Func<TState, Result> bind, CancellationToken cancellationToken = default)

    Chains an operation returning a new result on success, short-circuiting on failure.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    bind: Func<TState, Result>
    The binding function applied to the state and result to produce the next result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the result of the binding operation.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodEnsure
    public static Task<Result> Ensure(this Task<Result> resultTask, Func<bool> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this Task<Result>
    The task containing the source result.
    predicate: Func<bool>
    The condition to assert against the successful result.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

  • methodEnsure
    public static ValueTask<Result> Ensure(this ValueTask<Result> resultTask, Func<bool> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    predicate: Func<bool>
    The condition to assert against the successful result.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

  • methodEnsure<T>
    public static Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<T, Task<bool>> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    predicate: Func<T, Task<bool>>
    The condition to assert against the success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: T: The type of the source result value.

  • methodEnsure<T>
    public static Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<T, bool> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    predicate: Func<T, bool>
    The condition to assert against the success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: T: The type of the source result value.

  • methodEnsure<T>
    public static ValueTask<Result<T>> Ensure<T>(this ValueTask<Result<T>> resultTask, Func<T, ValueTask<bool>> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    predicate: Func<T, ValueTask<bool>>
    The condition to assert against the success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: T: The type of the source result value.

  • methodEnsure<T>
    public static ValueTask<Result<T>> Ensure<T>(this ValueTask<Result<T>> resultTask, Func<T, bool> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    predicate: Func<T, bool>
    The condition to assert against the success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: T: The type of the source result value.

  • methodEnsure<TState, T>
    public static Task<Result<T>> Ensure<TState, T>(this Task<Result<T>> resultTask, TState state, Func<TState, T, Task<bool>> predicate, Error error, CancellationToken cancellationToken = default)

    Applies an async predicate with captured `TState` to the success value of a `Task<TResult>` wrapping a `Result<T>`, avoiding closure allocations.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    predicate: Func<TState, T, Task<bool>>
    The condition to assert against the state and success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodEnsure<TState, T>
    public static Task<Result<T>> Ensure<TState, T>(this Task<Result<T>> resultTask, TState state, Func<TState, T, bool> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    predicate: Func<TState, T, bool>
    The condition to assert against the state and success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodEnsure<TState, T>
    public static ValueTask<Result<T>> Ensure<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, T, ValueTask<bool>> predicate, Error error, CancellationToken cancellationToken = default)

    Applies an async predicate with captured `TState` to the success value of a `ValueTask<TResult>` wrapping a `Result<T>`, avoiding closure allocations.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    predicate: Func<TState, T, ValueTask<bool>>
    The condition to assert against the state and success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodEnsure<TState, T>
    public static ValueTask<Result<T>> Ensure<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, T, bool> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    predicate: Func<TState, T, bool>
    The condition to assert against the state and success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodEnsure<TState>
    public static Task<Result> Ensure<TState>(this Task<Result> resultTask, TState state, Func<TState, bool> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    predicate: Func<TState, bool>
    The condition to assert against the state and success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodEnsure<TState>
    public static ValueTask<Result> Ensure<TState>(this ValueTask<Result> resultTask, TState state, Func<TState, bool> predicate, Error error, CancellationToken cancellationToken = default)

    Asserts a predicate against the asynchronous result, converting to a failure if the predicate evaluates to `false`.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    predicate: Func<TState, bool>
    The condition to assert against the state and success value.
    error: Error
    The error to return if the predicate evaluates to `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result if the predicate is satisfied, or a failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodExecute
    public static Task Execute(this Task<Result> resultTask, Action onSuccess, Action<Error> onFailure, CancellationToken cancellationToken = default)

    Executes an action based on whether the asynchronous result succeeded or failed.

    resultTask: this Task<Result>
    The task containing the source result.
    onSuccess: Action
    The action executed when the result is successful.
    onFailure: Action<Error>
    The action executed when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation.

  • methodExecute
    public static ValueTask Execute(this ValueTask<Result> resultTask, Action onSuccess, Action<Error> onFailure, CancellationToken cancellationToken = default)

    Executes an action based on whether the asynchronous result succeeded or failed.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    onSuccess: Action
    The action executed when the result is successful.
    onFailure: Action<Error>
    The action executed when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation.

  • methodExecute<T>
    public static Task Execute<T>(this Task<Result<T>> resultTask, Action<T> onSuccess, Action<Error> onFailure, CancellationToken cancellationToken = default)

    Executes an action based on whether the asynchronous result succeeded or failed.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    onSuccess: Action<T>
    The action executed when the result is successful.
    onFailure: Action<Error>
    The action executed when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation.

    Type parameters: T: The type of the source result value.

  • methodExecute<T>
    public static ValueTask Execute<T>(this ValueTask<Result<T>> resultTask, Action<T> onSuccess, Action<Error> onFailure, CancellationToken cancellationToken = default)

    Executes an action based on whether the asynchronous result succeeded or failed.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    onSuccess: Action<T>
    The action executed when the result is successful.
    onFailure: Action<Error>
    The action executed when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation.

    Type parameters: T: The type of the source result value.

  • methodExecute<TState, T>
    public static Task Execute<TState, T>(this Task<Result<T>> resultTask, TState state, Action<TState, T> onSuccess, Action<TState, Error> onFailure, CancellationToken cancellationToken = default)

    Executes an action based on whether the asynchronous result succeeded or failed.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Action<TState, T>
    The action executed with the state and success value when the result is successful.
    onFailure: Action<TState, Error>
    The action executed with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodExecute<TState, T>
    public static ValueTask Execute<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Action<TState, T> onSuccess, Action<TState, Error> onFailure, CancellationToken cancellationToken = default)

    Executes an action based on whether the asynchronous result succeeded or failed.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Action<TState, T>
    The action executed with the state and success value when the result is successful.
    onFailure: Action<TState, Error>
    The action executed with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodExecute<TState>
    public static Task Execute<TState>(this Task<Result> resultTask, TState state, Action<TState> onSuccess, Action<TState, Error> onFailure, CancellationToken cancellationToken = default)

    Executes an action based on whether the asynchronous result succeeded or failed.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Action<TState>
    The action executed with the state and success value when the result is successful.
    onFailure: Action<TState, Error>
    The action executed with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodExecute<TState>
    public static ValueTask Execute<TState>(this ValueTask<Result> resultTask, TState state, Action<TState> onSuccess, Action<TState, Error> onFailure, CancellationToken cancellationToken = default)

    Executes an action based on whether the asynchronous result succeeded or failed.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Action<TState>
    The action executed with the state and success value when the result is successful.
    onFailure: Action<TState, Error>
    The action executed with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodInspect
    public static Task<Result> Inspect(this Task<Result> resultTask, Action<Result> action, CancellationToken cancellationToken = default)

    Executes an inspection action on the asynchronous result regardless of its success or failure state.

    resultTask: this Task<Result>
    The task containing the source result.
    action: Action<Result>
    The side-effect action to execute with the evaluated result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

  • methodInspect
    public static ValueTask<Result> Inspect(this ValueTask<Result> resultTask, Action<Result> action, CancellationToken cancellationToken = default)

    Executes an inspection action on the asynchronous result regardless of its success or failure state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    action: Action<Result>
    The side-effect action to execute with the evaluated result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

  • methodInspect<T>
    public static Task<Result<T>> Inspect<T>(this Task<Result<T>> resultTask, Action<Result<T>> action, CancellationToken cancellationToken = default)

    Executes an inspection action on the asynchronous result regardless of its success or failure state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    action: Action<Result<T>>
    The side-effect action to execute with the evaluated result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodInspect<T>
    public static ValueTask<Result<T>> Inspect<T>(this ValueTask<Result<T>> resultTask, Action<Result<T>> action, CancellationToken cancellationToken = default)

    Executes an inspection action on the asynchronous result regardless of its success or failure state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    action: Action<Result<T>>
    The side-effect action to execute with the evaluated result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodInspect<TState, T>
    public static Task<Result<T>> Inspect<TState, T>(this Task<Result<T>> resultTask, TState state, Action<TState, Result<T>> action, CancellationToken cancellationToken = default)

    Executes an inspection action on the asynchronous result regardless of its success or failure state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    action: Action<TState, Result<T>>
    The side-effect action to execute with the evaluated result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodInspect<TState, T>
    public static ValueTask<Result<T>> Inspect<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Action<TState, Result<T>> action, CancellationToken cancellationToken = default)

    Executes an inspection action on the asynchronous result regardless of its success or failure state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    action: Action<TState, Result<T>>
    The side-effect action to execute with the evaluated result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodInspect<TState>
    public static Task<Result> Inspect<TState>(this Task<Result> resultTask, TState state, Action<TState, Result> action, CancellationToken cancellationToken = default)

    Executes an inspection action on the asynchronous result regardless of its success or failure state.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    action: Action<TState, Result>
    The side-effect action to execute with the evaluated result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodInspect<TState>
    public static ValueTask<Result> Inspect<TState>(this ValueTask<Result> resultTask, TState state, Action<TState, Result> action, CancellationToken cancellationToken = default)

    Executes an inspection action on the asynchronous result regardless of its success or failure state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    action: Action<TState, Result>
    The side-effect action to execute with the evaluated result.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodMap<T, TNext>
    public static Task<Result<TNext>> Map<T, TNext>(this Task<Result<T>> resultTask, Func<T, TNext> mapper, CancellationToken cancellationToken = default)

    Transforms the value of the asynchronous result using the specified mapping function on success.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    mapper: Func<T, TNext>
    The mapping function applied to the success value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: T: The type of the source result value.; TNext: The type of the transformed value.

  • methodMap<T, TNext>
    public static Task<Result<TNext>> Map<T, TNext>(this Task<Result<T>> resultTask, Func<T, Task<TNext>> mapper, CancellationToken cancellationToken = default)

    Transforms the value of the asynchronous result using the specified mapping function on success.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    mapper: Func<T, Task<TNext>>
    The mapping function applied to the success value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: T: The type of the source result value.; TNext: The type of the transformed value.

  • methodMap<T, TNext>
    public static ValueTask<Result<TNext>> Map<T, TNext>(this ValueTask<Result<T>> resultTask, Func<T, TNext> mapper, CancellationToken cancellationToken = default)

    Transforms the value of the asynchronous result using the specified mapping function on success.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    mapper: Func<T, TNext>
    The mapping function applied to the success value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: T: The type of the source result value.; TNext: The type of the transformed value.

  • methodMap<T, TNext>
    public static ValueTask<Result<TNext>> Map<T, TNext>(this ValueTask<Result<T>> resultTask, Func<T, ValueTask<TNext>> mapper, CancellationToken cancellationToken = default)

    Transforms the value of the asynchronous result using the specified mapping function on success.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    mapper: Func<T, ValueTask<TNext>>
    The mapping function applied to the success value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: T: The type of the source result value.; TNext: The type of the transformed value.

  • methodMap<TNext>
    public static Task<Result<TNext>> Map<TNext>(this Task<Result> resultTask, Func<CancellationToken, Task<TNext>> mapper, CancellationToken cancellationToken = default)

    Projects a successful `Result` into a `Result<TNext>` by executing an async `mapper` that receives a `CancellationToken`. If the Result is a failure, returns a failure without invoking `mapper`.

    resultTask: this Task<Result>
    The task containing the source result.
    mapper: Func<CancellationToken, Task<TNext>>
    The mapping function producing a new value on success.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodMap<TNext>
    public static Task<Result<TNext>> Map<TNext>(this Task<Result> resultTask, Func<TNext> mapper, CancellationToken cancellationToken = default)

    Projects a successful `Result` into a `Result<TNext>` by executing `mapper` on success. If the Result is a failure, returns a failure without invoking `mapper`.

    resultTask: this Task<Result>
    The task containing the source result.
    mapper: Func<TNext>
    The mapping function producing a new value on success.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodMap<TNext>
    public static ValueTask<Result<TNext>> Map<TNext>(this ValueTask<Result> resultTask, Func<CancellationToken, ValueTask<TNext>> mapper, CancellationToken cancellationToken = default)

    Projects a successful `Result` into a `Result<TNext>` by executing an async `mapper` that receives a `CancellationToken`. If the Result is a failure, returns a failure without invoking `mapper`.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    mapper: Func<CancellationToken, ValueTask<TNext>>
    The mapping function producing a new value on success.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodMap<TNext>
    public static ValueTask<Result<TNext>> Map<TNext>(this ValueTask<Result> resultTask, Func<TNext> mapper, CancellationToken cancellationToken = default)

    Projects a successful `Result` into a `Result<TNext>` by executing `mapper` on success. If the Result is a failure, returns a failure without invoking `mapper`.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    mapper: Func<TNext>
    The mapping function producing a new value on success.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TNext: The type of the transformed value.

  • methodMap<TState, T, TNext>
    public static Task<Result<TNext>> Map<TState, T, TNext>(this Task<Result<T>> resultTask, TState state, Func<TState, T, TNext> mapper, CancellationToken cancellationToken = default)

    Transforms the value of the asynchronous result using the specified mapping function on success.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, T, TNext>
    The mapping function applied to the state and success value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TNext: The type of the transformed value.

  • methodMap<TState, T, TNext>
    public static Task<Result<TNext>> Map<TState, T, TNext>(this Task<Result<T>> resultTask, TState state, Func<TState, T, Task<TNext>> mapper, CancellationToken cancellationToken = default)

    Maps the success value of a `Task<TResult>` wrapping a `Result<T>` using an async mapper with captured `TState` to avoid closure allocations.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, T, Task<TNext>>
    The mapping function applied to the state and success value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TNext: The type of the transformed value.

  • methodMap<TState, T, TNext>
    public static ValueTask<Result<TNext>> Map<TState, T, TNext>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, T, TNext> mapper, CancellationToken cancellationToken = default)

    Transforms the value of the asynchronous result using the specified mapping function on success.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, T, TNext>
    The mapping function applied to the state and success value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TNext: The type of the transformed value.

  • methodMap<TState, T, TNext>
    public static ValueTask<Result<TNext>> Map<TState, T, TNext>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, T, ValueTask<TNext>> mapper, CancellationToken cancellationToken = default)

    Maps the success value of a `ValueTask<TResult>` wrapping a `Result<T>` using an async mapper with captured `TState` to avoid closure allocations.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, T, ValueTask<TNext>>
    The mapping function applied to the state and success value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TNext: The type of the transformed value.

  • methodMap<TState, TNext>
    public static Task<Result<TNext>> Map<TState, TNext>(this Task<Result> resultTask, TState state, Func<TState, TNext> mapper, CancellationToken cancellationToken = default)

    Projects a successful `Result` into a `Result<TNext>` using a state argument to avoid closure allocations.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, TNext>
    The mapping function applied to the state to produce a new value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TNext: The type of the transformed value.

  • methodMap<TState, TNext>
    public static ValueTask<Result<TNext>> Map<TState, TNext>(this ValueTask<Result> resultTask, TState state, Func<TState, TNext> mapper, CancellationToken cancellationToken = default)

    Projects a successful `Result` into a `Result<TNext>` using a state argument to avoid closure allocations.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, TNext>
    The mapping function applied to the state to produce a new value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a `Result<TNext>` with the mapped value on success, or the original failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TNext: The type of the transformed value.

  • methodMapError
    public static Task<Result> MapError(this Task<Result> resultTask, Func<Error, Error> mapper, CancellationToken cancellationToken = default)

    Transforms the inner error of the asynchronous result if in a failure state.

    resultTask: this Task<Result>
    The task containing the source result.
    mapper: Func<Error, Error>
    The mapping function applied to the error on failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result on success, or a failure with the transformed error.

  • methodMapError
    public static ValueTask<Result> MapError(this ValueTask<Result> resultTask, Func<Error, Error> mapper, CancellationToken cancellationToken = default)

    Transforms the inner error of the asynchronous result if in a failure state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    mapper: Func<Error, Error>
    The mapping function applied to the error on failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result on success, or a failure with the transformed error.

  • methodMapError<T>
    public static Task<Result<T>> MapError<T>(this Task<Result<T>> resultTask, Func<Error, Error> mapper, CancellationToken cancellationToken = default)

    Transforms the inner error of the asynchronous result if in a failure state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    mapper: Func<Error, Error>
    The mapping function applied to the error on failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result on success, or a failure with the transformed error.

    Type parameters: T: The type of the success value.

  • methodMapError<T>
    public static ValueTask<Result<T>> MapError<T>(this ValueTask<Result<T>> resultTask, Func<Error, Error> mapper, CancellationToken cancellationToken = default)

    Transforms the inner error of the asynchronous result if in a failure state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    mapper: Func<Error, Error>
    The mapping function applied to the error on failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result on success, or a failure with the transformed error.

    Type parameters: T: The type of the success value.

  • methodMapError<TState, T>
    public static Task<Result<T>> MapError<TState, T>(this Task<Result<T>> resultTask, TState state, Func<TState, Error, Error> mapper, CancellationToken cancellationToken = default)

    Transforms the inner error of the asynchronous result if in a failure state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, Error, Error>
    The mapping function applied to the state and error on failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result on success, or a failure with the transformed error.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the success value.

  • methodMapError<TState, T>
    public static ValueTask<Result<T>> MapError<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, Error, Error> mapper, CancellationToken cancellationToken = default)

    Transforms the inner error of the asynchronous result if in a failure state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, Error, Error>
    The mapping function applied to the state and error on failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result on success, or a failure with the transformed error.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the success value.

  • methodMapError<TState>
    public static Task<Result> MapError<TState>(this Task<Result> resultTask, TState state, Func<TState, Error, Error> mapper, CancellationToken cancellationToken = default)

    Transforms the inner error of the asynchronous result if in a failure state.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, Error, Error>
    The mapping function applied to the state and error on failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result on success, or a failure with the transformed error.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodMapError<TState>
    public static ValueTask<Result> MapError<TState>(this ValueTask<Result> resultTask, TState state, Func<TState, Error, Error> mapper, CancellationToken cancellationToken = default)

    Transforms the inner error of the asynchronous result if in a failure state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    mapper: Func<TState, Error, Error>
    The mapping function applied to the state and error on failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result on success, or a failure with the transformed error.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodMapFailure<T, TOut>
    public static Task<TOut> MapFailure<T, TOut>(this Task<Result<T>> resultTask, Func<Error, TOut> onFailure, TOut successDefault, CancellationToken cancellationToken = default)

    Maps a failure error into `TOut` using `onFailure`, or returns `successDefault` when the result is successful. Async overload for `Task<Result<T>>` pipelines.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    onFailure: Func<Error, TOut>
    The function applied to the error to produce a fallback value on failure.
    successDefault: TOut
    The default value to return when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the mapped failure value, or the default value on success.

    Type parameters: T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMapFailure<T, TOut>
    public static ValueTask<TOut> MapFailure<T, TOut>(this ValueTask<Result<T>> resultTask, Func<Error, TOut> onFailure, TOut successDefault, CancellationToken cancellationToken = default)

    Maps a failure error into `TOut` using `onFailure`, or returns `successDefault` when the result is successful. Async overload for `ValueTask<Result<T>>` pipelines.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    onFailure: Func<Error, TOut>
    The function applied to the error to produce a fallback value on failure.
    successDefault: TOut
    The default value to return when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the mapped failure value, or the default value on success.

    Type parameters: T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMapFailure<TOut>
    public static Task<TOut> MapFailure<TOut>(this Task<Result> resultTask, Func<Error, TOut> onFailure, TOut successDefault, CancellationToken cancellationToken = default)

    Maps a failure error into `TOut` using `onFailure`, or returns `successDefault` when the result is successful. Async overload for `Task<Result>` pipelines.

    resultTask: this Task<Result>
    The task containing the source result.
    onFailure: Func<Error, TOut>
    The function applied to the error to produce a fallback value on failure.
    successDefault: TOut
    The default value to return when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the mapped failure value, or the default value on success.

    Type parameters: TOut: The type of the value produced by the projection.

  • methodMapFailure<TOut>
    public static ValueTask<TOut> MapFailure<TOut>(this ValueTask<Result> resultTask, Func<Error, TOut> onFailure, TOut successDefault, CancellationToken cancellationToken = default)

    Maps a failure error into `TOut` using `onFailure`, or returns `successDefault` when the result is successful. Async overload for `ValueTask<Result>` pipelines.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    onFailure: Func<Error, TOut>
    The function applied to the error to produce a fallback value on failure.
    successDefault: TOut
    The default value to return when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the mapped failure value, or the default value on success.

    Type parameters: TOut: The type of the value produced by the projection.

  • methodMapFailure<TState, T, TOut>
    public static Task<TOut> MapFailure<TState, T, TOut>(this Task<Result<T>> resultTask, TState state, Func<TState, Error, TOut> onFailure, TOut successDefault, CancellationToken cancellationToken = default)

    Maps a failure error into `TOut` using captured state to avoid closure allocations. Async overload for `Task<Result<T>>` pipelines.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onFailure: Func<TState, Error, TOut>
    The function applied to the state and error to produce a fallback value on failure.
    successDefault: TOut
    The default value to return when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the mapped failure value, or the default value on success.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMapFailure<TState, T, TOut>
    public static ValueTask<TOut> MapFailure<TState, T, TOut>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, Error, TOut> onFailure, TOut successDefault, CancellationToken cancellationToken = default)

    Maps a failure error into `TOut` using captured state to avoid closure allocations. Async overload for `ValueTask<Result<T>>` pipelines.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onFailure: Func<TState, Error, TOut>
    The function applied to the state and error to produce a fallback value on failure.
    successDefault: TOut
    The default value to return when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the mapped failure value, or the default value on success.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMapFailure<TState, TOut>
    public static Task<TOut> MapFailure<TState, TOut>(this Task<Result> resultTask, TState state, Func<TState, Error, TOut> onFailure, TOut successDefault, CancellationToken cancellationToken = default)

    Maps a failure error into `TOut` using captured state to avoid closure allocations. Async overload for `Task<Result>` pipelines.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onFailure: Func<TState, Error, TOut>
    The function applied to the state and error to produce a fallback value on failure.
    successDefault: TOut
    The default value to return when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the mapped failure value, or the default value on success.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TOut: The type of the value produced by the projection.

  • methodMapFailure<TState, TOut>
    public static ValueTask<TOut> MapFailure<TState, TOut>(this ValueTask<Result> resultTask, TState state, Func<TState, Error, TOut> onFailure, TOut successDefault, CancellationToken cancellationToken = default)

    Maps a failure error into `TOut` using captured state to avoid closure allocations. Async overload for `ValueTask<Result>` pipelines.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onFailure: Func<TState, Error, TOut>
    The function applied to the state and error to produce a fallback value on failure.
    successDefault: TOut
    The default value to return when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the mapped failure value, or the default value on success.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TOut: The type of the value produced by the projection.

  • methodMatch<T, TOut>
    public static Task<TOut> Match<T, TOut>(this Task<Result<T>> resultTask, Func<T, TOut> onSuccess, Func<Error, TOut> onFailure)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    onSuccess: Func<T, TOut>
    The function invoked when the result is successful.
    onFailure: Func<Error, TOut>
    The function invoked when the result is a failure.

    Returns: A task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMatch<T, TOut>
    public static Task<TOut> Match<T, TOut>(this Task<Result<T>> resultTask, Func<T, TOut> onSuccess, Func<Error, TOut> onFailure, CancellationToken cancellationToken)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    onSuccess: Func<T, TOut>
    The function invoked when the result is successful.
    onFailure: Func<Error, TOut>
    The function invoked when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMatch<T, TOut>
    public static ValueTask<TOut> Match<T, TOut>(this ValueTask<Result<T>> resultTask, Func<T, TOut> onSuccess, Func<Error, TOut> onFailure)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    onSuccess: Func<T, TOut>
    The function invoked when the result is successful.
    onFailure: Func<Error, TOut>
    The function invoked when the result is a failure.

    Returns: A value task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMatch<T, TOut>
    public static ValueTask<TOut> Match<T, TOut>(this ValueTask<Result<T>> resultTask, Func<T, TOut> onSuccess, Func<Error, TOut> onFailure, CancellationToken cancellationToken)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    onSuccess: Func<T, TOut>
    The function invoked when the result is successful.
    onFailure: Func<Error, TOut>
    The function invoked when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMatch<TOut>
    public static Task<TOut> Match<TOut>(this Task<Result> resultTask, Func<TOut> onSuccess, Func<Error, TOut> onFailure)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this Task<Result>
    The task containing the source result.
    onSuccess: Func<TOut>
    The function invoked when the result is successful.
    onFailure: Func<Error, TOut>
    The function invoked when the result is a failure.

    Returns: A task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TOut: The type of the value produced by the projection.

  • methodMatch<TOut>
    public static Task<TOut> Match<TOut>(this Task<Result> resultTask, Func<TOut> onSuccess, Func<Error, TOut> onFailure, CancellationToken cancellationToken)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this Task<Result>
    The task containing the source result.
    onSuccess: Func<TOut>
    The function invoked when the result is successful.
    onFailure: Func<Error, TOut>
    The function invoked when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TOut: The type of the value produced by the projection.

  • methodMatch<TOut>
    public static ValueTask<TOut> Match<TOut>(this ValueTask<Result> resultTask, Func<TOut> onSuccess, Func<Error, TOut> onFailure)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    onSuccess: Func<TOut>
    The function invoked when the result is successful.
    onFailure: Func<Error, TOut>
    The function invoked when the result is a failure.

    Returns: A value task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TOut: The type of the value produced by the projection.

  • methodMatch<TOut>
    public static ValueTask<TOut> Match<TOut>(this ValueTask<Result> resultTask, Func<TOut> onSuccess, Func<Error, TOut> onFailure, CancellationToken cancellationToken)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    onSuccess: Func<TOut>
    The function invoked when the result is successful.
    onFailure: Func<Error, TOut>
    The function invoked when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TOut: The type of the value produced by the projection.

  • methodMatch<TState, T, TOut>
    public static Task<TOut> Match<TState, T, TOut>(this Task<Result<T>> resultTask, TState state, Func<TState, T, TOut> onSuccess, Func<TState, Error, TOut> onFailure)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Func<TState, T, TOut>
    The function invoked with the state and success value when the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function invoked with the state and error when the result is a failure.

    Returns: A task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMatch<TState, T, TOut>
    public static Task<TOut> Match<TState, T, TOut>(this Task<Result<T>> resultTask, TState state, Func<TState, T, TOut> onSuccess, Func<TState, Error, TOut> onFailure, CancellationToken cancellationToken)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Func<TState, T, TOut>
    The function invoked with the state and success value when the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function invoked with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMatch<TState, T, TOut>
    public static ValueTask<TOut> Match<TState, T, TOut>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, T, TOut> onSuccess, Func<TState, Error, TOut> onFailure)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Func<TState, T, TOut>
    The function invoked with the state and success value when the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function invoked with the state and error when the result is a failure.

    Returns: A value task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMatch<TState, T, TOut>
    public static ValueTask<TOut> Match<TState, T, TOut>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, T, TOut> onSuccess, Func<TState, Error, TOut> onFailure, CancellationToken cancellationToken)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Func<TState, T, TOut>
    The function invoked with the state and success value when the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function invoked with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.; TOut: The type of the value produced by the projection.

  • methodMatch<TState, TOut>
    public static Task<TOut> Match<TState, TOut>(this Task<Result> resultTask, TState state, Func<TState, TOut> onSuccess, Func<TState, Error, TOut> onFailure)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Func<TState, TOut>
    The function invoked with the state and success value when the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function invoked with the state and error when the result is a failure.

    Returns: A task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TOut: The type of the value produced by the projection.

  • methodMatch<TState, TOut>
    public static Task<TOut> Match<TState, TOut>(this Task<Result> resultTask, TState state, Func<TState, TOut> onSuccess, Func<TState, Error, TOut> onFailure, CancellationToken cancellationToken)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Func<TState, TOut>
    The function invoked with the state and success value when the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function invoked with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TOut: The type of the value produced by the projection.

  • methodMatch<TState, TOut>
    public static ValueTask<TOut> Match<TState, TOut>(this ValueTask<Result> resultTask, TState state, Func<TState, TOut> onSuccess, Func<TState, Error, TOut> onFailure)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Func<TState, TOut>
    The function invoked with the state and success value when the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function invoked with the state and error when the result is a failure.

    Returns: A value task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TOut: The type of the value produced by the projection.

  • methodMatch<TState, TOut>
    public static ValueTask<TOut> Match<TState, TOut>(this ValueTask<Result> resultTask, TState state, Func<TState, TOut> onSuccess, Func<TState, Error, TOut> onFailure, CancellationToken cancellationToken)

    Matches the asynchronous result, executing the appropriate projection function based on the outcome.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Func<TState, TOut>
    The function invoked with the state and success value when the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function invoked with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the value produced by the invoked branch.

    Type parameters: TState: The type of the state data forwarded to the delegate.; TOut: The type of the value produced by the projection.

  • methodRecover
    public static Task<Result> Recover(this Task<Result> resultTask, Func<Error, Result> recovery, CancellationToken cancellationToken = default)

    If the `Result` is a failure, invokes `recovery` to attempt a corrective result. If the Result is a success, returns it unchanged.

    resultTask: this Task<Result>
    The task containing the source result.
    recovery: Func<Error, Result>
    The recovery function producing a fallback from the error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a successful result, or the recovered result on failure.

  • methodRecover
    public static Task<Result> Recover(this Task<Result> resultTask, Func<Error, Task<Result>> recovery, CancellationToken cancellationToken = default)

    If the `Result` is a failure, invokes the async `recovery` delegate to attempt a corrective result.

    resultTask: this Task<Result>
    The task containing the source result.
    recovery: Func<Error, Task<Result>>
    The recovery function producing a fallback from the error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a successful result, or the recovered result on failure.

  • methodRecover
    public static ValueTask<Result> Recover(this ValueTask<Result> resultTask, Func<Error, Result> recovery, CancellationToken cancellationToken = default)

    If the `Result` is a failure, invokes `recovery` to attempt a corrective result. If the Result is a success, returns it unchanged.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    recovery: Func<Error, Result>
    The recovery function producing a fallback from the error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a successful result, or the recovered result on failure.

  • methodRecover
    public static ValueTask<Result> Recover(this ValueTask<Result> resultTask, Func<Error, ValueTask<Result>> recovery, CancellationToken cancellationToken = default)

    If the `Result` is a failure, invokes the async `recovery` delegate to attempt a corrective result.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    recovery: Func<Error, ValueTask<Result>>
    The recovery function producing a fallback from the error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a successful result, or the recovered result on failure.

  • methodRecover<T>
    public static Task<Result<T>> Recover<T>(this Task<Result<T>> resultTask, Func<Error, Result<T>> recovery, CancellationToken cancellationToken = default)

    Intercepts a failure in the asynchronous result and returns an alternative fallback value or computation.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    recovery: Func<Error, Result<T>>
    The recovery function producing a fallback from the error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result on success, or the recovered result on failure.

    Type parameters: T: The type of the source result value.

  • methodRecover<T>
    public static Task<Result<T>> Recover<T>(this Task<Result<T>> resultTask, Func<Error, Task<Result<T>>> recovery, CancellationToken cancellationToken = default)

    Intercepts a failure in the asynchronous result and returns an alternative fallback value or computation.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    recovery: Func<Error, Task<Result<T>>>
    The recovery function producing a fallback from the error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result on success, or the recovered result on failure.

    Type parameters: T: The type of the source result value.

  • methodRecover<T>
    public static ValueTask<Result<T>> Recover<T>(this ValueTask<Result<T>> resultTask, Func<Error, Result<T>> recovery, CancellationToken cancellationToken = default)

    Intercepts a failure in the asynchronous result and returns an alternative fallback value or computation.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    recovery: Func<Error, Result<T>>
    The recovery function producing a fallback from the error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result on success, or the recovered result on failure.

    Type parameters: T: The type of the source result value.

  • methodRecover<T>
    public static ValueTask<Result<T>> Recover<T>(this ValueTask<Result<T>> resultTask, Func<Error, ValueTask<Result<T>>> recovery, CancellationToken cancellationToken = default)

    Intercepts a failure in the asynchronous result and returns an alternative fallback value or computation.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    recovery: Func<Error, ValueTask<Result<T>>>
    The recovery function producing a fallback from the error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result on success, or the recovered result on failure.

    Type parameters: T: The type of the source result value.

  • methodRecover<TState, T>
    public static Task<Result<T>> Recover<TState, T>(this Task<Result<T>> resultTask, TState state, Func<TState, Error, Result<T>> recovery, CancellationToken cancellationToken = default)

    Intercepts a failure in the asynchronous result and returns an alternative fallback value or computation.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    recovery: Func<TState, Error, Result<T>>
    The recovery function producing a fallback from the state and error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result on success, or the recovered result on failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodRecover<TState, T>
    public static Task<Result<T>> Recover<TState, T>(this Task<Result<T>> resultTask, TState state, Func<TState, Error, Task<Result<T>>> recovery, CancellationToken cancellationToken = default)

    Attempts to recover from a failure using an async recovery function with captured `TState`, avoiding closure allocations.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    recovery: Func<TState, Error, Task<Result<T>>>
    The recovery function producing a fallback from the state and error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result on success, or the recovered result on failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodRecover<TState, T>
    public static ValueTask<Result<T>> Recover<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, Error, Result<T>> recovery, CancellationToken cancellationToken = default)

    Intercepts a failure in the asynchronous result and returns an alternative fallback value or computation.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    recovery: Func<TState, Error, Result<T>>
    The recovery function producing a fallback from the state and error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result on success, or the recovered result on failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodRecover<TState, T>
    public static ValueTask<Result<T>> Recover<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Func<TState, Error, ValueTask<Result<T>>> recovery, CancellationToken cancellationToken = default)

    Attempts to recover from a failure using an async recovery function with captured `TState`, avoiding closure allocations.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    recovery: Func<TState, Error, ValueTask<Result<T>>>
    The recovery function producing a fallback from the state and error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result on success, or the recovered result on failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodRecover<TState>
    public static Task<Result> Recover<TState>(this Task<Result> resultTask, TState state, Func<TState, Error, Result> recovery, CancellationToken cancellationToken = default)

    If the `Result` is a failure, invokes `recovery` with captured state to attempt a corrective result.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    recovery: Func<TState, Error, Result>
    The recovery function producing a fallback from the state and error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a successful result, or the recovered result on failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodRecover<TState>
    public static ValueTask<Result> Recover<TState>(this ValueTask<Result> resultTask, TState state, Func<TState, Error, Result> recovery, CancellationToken cancellationToken = default)

    If the `Result` is a failure, invokes `recovery` with state to attempt a corrective result.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    recovery: Func<TState, Error, Result>
    The recovery function producing a fallback from the state and error.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains a successful result, or the recovered result on failure.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodTapOnFailure
    public static Task<Result> TapOnFailure(this Task<Result> resultTask, Action<Error> onFailure, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this Task<Result>
    The task containing the source result.
    onFailure: Action<Error>
    The action executed when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

  • methodTapOnFailure
    public static Task<Result> TapOnFailure(this Task<Result> resultTask, Func<Error, Task> onFailure, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this Task<Result>
    The task containing the source result.
    onFailure: Func<Error, Task>
    The action executed when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

  • methodTapOnFailure
    public static ValueTask<Result> TapOnFailure(this ValueTask<Result> resultTask, Action<Error> onFailure, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    onFailure: Action<Error>
    The action executed when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

  • methodTapOnFailure
    public static ValueTask<Result> TapOnFailure(this ValueTask<Result> resultTask, Func<Error, ValueTask> onFailure, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    onFailure: Func<Error, ValueTask>
    The action executed when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

  • methodTapOnFailure<T>
    public static Task<Result<T>> TapOnFailure<T>(this Task<Result<T>> resultTask, Action<Error> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    action: Action<Error>
    The side-effect action to execute if the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodTapOnFailure<T>
    public static Task<Result<T>> TapOnFailure<T>(this Task<Result<T>> resultTask, Func<Error, Task> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    action: Func<Error, Task>
    The side-effect action to execute if the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodTapOnFailure<T>
    public static ValueTask<Result<T>> TapOnFailure<T>(this ValueTask<Result<T>> resultTask, Action<Error> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    action: Action<Error>
    The side-effect action to execute if the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodTapOnFailure<T>
    public static ValueTask<Result<T>> TapOnFailure<T>(this ValueTask<Result<T>> resultTask, Func<Error, ValueTask> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    action: Func<Error, ValueTask>
    The side-effect action to execute if the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodTapOnFailure<TState, T>
    public static Task<Result<T>> TapOnFailure<TState, T>(this Task<Result<T>> resultTask, TState state, Action<TState, Error> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    action: Action<TState, Error>
    The side-effect action to execute if the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodTapOnFailure<TState, T>
    public static ValueTask<Result<T>> TapOnFailure<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Action<TState, Error> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    action: Action<TState, Error>
    The side-effect action to execute if the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodTapOnFailure<TState>
    public static Task<Result> TapOnFailure<TState>(this Task<Result> resultTask, TState state, Action<TState, Error> onFailure, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onFailure: Action<TState, Error>
    The action executed with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodTapOnFailure<TState>
    public static ValueTask<Result> TapOnFailure<TState>(this ValueTask<Result> resultTask, TState state, Action<TState, Error> onFailure, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a failure state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onFailure: Action<TState, Error>
    The action executed with the state and error when the result is a failure.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodTapOnSuccess
    public static Task<Result> TapOnSuccess(this Task<Result> resultTask, Action onSuccess, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this Task<Result>
    The task containing the source result.
    onSuccess: Action
    The action executed when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

  • methodTapOnSuccess
    public static Task<Result> TapOnSuccess(this Task<Result> resultTask, Func<Task> onSuccess, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this Task<Result>
    The task containing the source result.
    onSuccess: Func<Task>
    The action executed when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

  • methodTapOnSuccess
    public static ValueTask<Result> TapOnSuccess(this ValueTask<Result> resultTask, Action onSuccess, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    onSuccess: Action
    The action executed when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

  • methodTapOnSuccess
    public static ValueTask<Result> TapOnSuccess(this ValueTask<Result> resultTask, Func<ValueTask> onSuccess, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    onSuccess: Func<ValueTask>
    The action executed when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

  • methodTapOnSuccess<T>
    public static Task<Result<T>> TapOnSuccess<T>(this Task<Result<T>> resultTask, Action<T> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    action: Action<T>
    The side-effect action to execute if the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodTapOnSuccess<T>
    public static Task<Result<T>> TapOnSuccess<T>(this Task<Result<T>> resultTask, Func<T, Task> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    action: Func<T, Task>
    The side-effect action to execute if the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodTapOnSuccess<T>
    public static ValueTask<Result<T>> TapOnSuccess<T>(this ValueTask<Result<T>> resultTask, Action<T> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    action: Action<T>
    The side-effect action to execute if the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodTapOnSuccess<T>
    public static ValueTask<Result<T>> TapOnSuccess<T>(this ValueTask<Result<T>> resultTask, Func<T, ValueTask> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    action: Func<T, ValueTask>
    The side-effect action to execute if the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: T: The type of the source result value.

  • methodTapOnSuccess<TState, T>
    public static Task<Result<T>> TapOnSuccess<TState, T>(this Task<Result<T>> resultTask, TState state, Action<TState, T> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this Task<Result<T>>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    action: Action<TState, T>
    The side-effect action to execute if the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodTapOnSuccess<TState, T>
    public static ValueTask<Result<T>> TapOnSuccess<TState, T>(this ValueTask<Result<T>> resultTask, TState state, Action<TState, T> action, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this ValueTask<Result<T>>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    action: Action<TState, T>
    The side-effect action to execute if the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.; T: The type of the source result value.

  • methodTapOnSuccess<TState>
    public static Task<Result> TapOnSuccess<TState>(this Task<Result> resultTask, TState state, Action<TState> onSuccess, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this Task<Result>
    The task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Action<TState>
    The action executed with the state when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.

  • methodTapOnSuccess<TState>
    public static ValueTask<Result> TapOnSuccess<TState>(this ValueTask<Result> resultTask, TState state, Action<TState> onSuccess, CancellationToken cancellationToken = default)

    Executes a side-effect action if the asynchronous result is in a success state.

    resultTask: this ValueTask<Result>
    The value task containing the source result.
    state: TState
    The state data forwarded to the delegate to avoid closure allocations.
    onSuccess: Action<TState>
    The action executed with the state when the result is successful.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A value task representing the asynchronous operation. The task result contains the original result.

    Type parameters: TState: The type of the state data forwarded to the delegate.

class

ResultLinqExtensions

Assembly: EricksonLopez.Result
public static class ResultLinqExtensions

Provides LINQ extension support for `Result<TValue>` pipelines.

Members (3)

  • methodSelect<TSource, TResult>
    public static Result<TResult> Select<TSource, TResult>(this in Result<TSource> source, Func<TSource, TResult> selector)

    Projects the success value of a Result into a new form using LINQ query syntax.

    source: this in Result<TSource>
    The source result to project, passed by readonly reference.
    selector: Func<TSource, TResult>
    A transform function to apply to the source value.

    Returns: A new `Result<TResult>` containing the transformed value on success, or the original error on failure.

    Type parameters: TSource: The source value type.; TResult: The target value type produced by the selector. Exceptions: ArgumentNullException: `selector` is `null`; InvalidOperationException: `source` is an uninitialized default value

  • methodSelectMany<TSource, TCollection, TResult>
    public static Result<TResult> SelectMany<TSource, TCollection, TResult>(this in Result<TSource> source, Func<TSource, Result<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)

    Projects and flattens monadic Result pipelines using LINQ query syntax (from x in a from y in b select z).

    source: this in Result<TSource>
    The source result to project, passed by readonly reference.
    collectionSelector: Func<TSource, Result<TCollection>>
    A transform function to apply to the source value, returning an intermediate result.
    resultSelector: Func<TSource, TCollection, TResult>
    A transform function to apply to the source value and intermediate value.

    Returns: A new `Result<TResult>` containing the combined value on success, or the first encountered failure error.

    Type parameters: TSource: The source value type.; TCollection: The intermediate value type produced by the collection selector.; TResult: The target value type produced by the result selector. Exceptions: ArgumentNullException: `collectionSelector` or `resultSelector` is `null`; InvalidOperationException: `source` is an uninitialized default value

  • methodWhere<TSource>
    public static Result<TSource> Where<TSource>(this in Result<TSource> source, Func<TSource, bool> predicate)

    Filters the success value of a Result using a predicate, enabling LINQ `where` clause syntax. Returns a failure if the predicate returns `false` or if the source is already a failure.

    source: this in Result<TSource>
    The result to filter, passed by readonly reference.
    predicate: Func<TSource, bool>
    A function that tests the success value. Returns a failure with a generic validation error if the predicate returns `false`.

    Returns: The original result if it is a success and the predicate returns `true`; a failure result with a `ErrorType.Validation` error otherwise.

    Enables the LINQ `where` clause on `Result<TValue>` pipelines:

    var result =
        from order in GetOrder(id)
        where order.IsActive
        select order.Total;

    For richer control over the failure error (custom code, description, type), use `Result<TValue>.Ensure(Func<TValue, bool>, Error)` directly. Type parameters: TSource: The value type of the result. Exceptions: ArgumentNullException: `predicate` is `null`; InvalidOperationException: `source` is an uninitialized default value

class

ResultSyncExtensions

Assembly: EricksonLopez.Result
public static class ResultSyncExtensions

Provides high-performance synchronous extension methods for `Result<TValue>` that accept the struct by reference (`in`) to avoid copying large value types.

Remarks:

Performance rationale: When the value type parameter of `Result<T>` is a large value type (e.g., `decimal` at 16 bytes, `Guid` at 16 bytes, or value tuples beyond 8 bytes), passing `Result<T>` by value incurs a struct copy on the call site. These `in`-parameter overloads eliminate that copy by passing the struct by readonly reference. When to use: These extension methods are identical in behavior to the instance methods on `Result<TValue>` (e.g., `Result<TValue>.Map<TNext>`). They are provided as an explicit optimization path for scenarios where: - The value type parameter is a value type with size >= 16 bytes (e.g., `decimal`, `Guid`, large structs) - The result is passed across many layers and each layer calls at least one pipeline method - Profiling confirms struct-copy overhead in a hot path For reference types (`class`, `string`, `object`), `in` provides no measurable benefit because reference types are already passed as 8-byte pointers. Uninitialized contract: All monadic extension methods (`Map`, `Bind`, `Ensure`, `Match`) throw `InvalidOperationException` when called on an uninitialized `default(Result<T>)`, identical to the corresponding instance methods on `Result<TValue>`. The only exceptions are `TryGetValue<TValue>(in Result<TValue>, out TValue)` and `GetValueOrDefault<TValue>(in Result<TValue>, TValue)`, which follow the BCL `*OrDefault` convention and never throw — they return `false` / the default value for any non-Success state including Uninitialized. Naming: These are named identically to the instance methods to minimize friction. The compiler selects the `in` extension method when the caller has a local variable or field of type `Result<TValue>` and the code is `result.Map(...)` or directly called as `ResultSyncExtensions.Map(in result, ...)`.

Members (14)

  • methodBind<TValue, TNext>
    public static Result<TNext> Bind<TValue, TNext>(this in Result<TValue> result, Func<TValue, Result<TNext>> bind)

    Chains a monadic bind operation on `result`. The `in` parameter avoids copying the struct — use when `TValue` is a large value type (≥ 16 bytes).

    result: this in Result<TValue>
    The source result, passed by readonly reference.
    bind: Func<TValue, Result<TNext>>
    The operation to execute with the success value.

    Returns: The result of executing `bind` on success; otherwise, a failure with the original error.

    Type parameters: TValue: The source value type.; TNext: The output value type of the chained operation. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodBind<TValue, TState, TNext>
    public static Result<TNext> Bind<TValue, TState, TNext>(this in Result<TValue> result, TState state, Func<TState, TValue, Result<TNext>> bind)

    Chains a monadic bind operation on `result` with captured `state` to avoid closure allocation. The `in` parameter avoids copying the struct.

    result: this in Result<TValue>
    The source result, passed by readonly reference.
    state: TState
    The state value passed to the bind function.
    bind: Func<TState, TValue, Result<TNext>>
    The operation to execute with state and the success value.

    Returns: The result of executing `bind` on success; otherwise, a failure with the original error.

    Type parameters: TValue: The source value type.; TState: The type of the state object passed to the bind function.; TNext: The output value type of the chained operation. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodEnsure<TValue, TState>
    public static Result<TValue> Ensure<TValue, TState>(this in Result<TValue> result, TState state, Func<TState, TValue, bool> predicate, Error error)

    Validates the success value of `result` using `predicate` with captured `state` to avoid closure allocation. The `in` parameter avoids copying the struct.

    result: this in Result<TValue>
    The result to validate, passed by readonly reference.
    state: TState
    The state value passed to the predicate.
    predicate: Func<TState, TValue, bool>
    The condition to test on state and the success value.
    error: Error
    The error to return if the condition evaluates to `false`.

    Returns: The original result if valid or failed; otherwise, a failure with `error`.

    Type parameters: TValue: The source value type.; TState: The type of the state object passed to the predicate. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodEnsure<TValue, TState>
    public static Result<TValue> Ensure<TValue, TState>(this in Result<TValue> result, TState state, Func<TState, TValue, bool> predicate, Func<TState, Error> errorFactory)

    Validates the success value of `result` using `predicate` with captured `state` to avoid closure allocation. The error factory is only invoked when the predicate fails. The `in` parameter avoids copying the struct.

    result: this in Result<TValue>
    The result to validate, passed by readonly reference.
    state: TState
    The state value passed to the predicate and error factory.
    predicate: Func<TState, TValue, bool>
    The condition to test on state and the success value.
    errorFactory: Func<TState, Error>
    A factory that receives state and generates the error if the condition evaluates to `false`.

    Returns: The original result if valid or failed; otherwise, a failure with the generated error.

    Type parameters: TValue: The source value type.; TState: The type of the state object passed to the predicate and error factory. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodEnsure<TValue, TState>
    public static Result<TValue> Ensure<TValue, TState>(this in Result<TValue> result, TState state, Func<TState, TValue, bool> predicate, Func<TState, TValue, Error> errorFactory)

    Validates the success value of `result` using `predicate` with captured `state` to avoid closure allocation. The error factory receives both the state and the value for context-aware error construction. The `in` parameter avoids copying the struct.

    result: this in Result<TValue>
    The result to validate, passed by readonly reference.
    state: TState
    The state value passed to the predicate and error factory.
    predicate: Func<TState, TValue, bool>
    The condition to test on state and the success value.
    errorFactory: Func<TState, TValue, Error>
    A factory that receives state and value to generate the error if the condition evaluates to `false`.

    Returns: The original result if valid or failed; otherwise, a failure with the generated error.

    Type parameters: TValue: The source value type.; TState: The type of the state object passed to the predicate and error factory. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodEnsure<TValue>
    public static Result<TValue> Ensure<TValue>(this in Result<TValue> result, Func<TValue, bool> predicate, Error error)

    Validates the success value of `result` using `predicate`. Returns a failure with `error` if the predicate returns `false`. The `in` parameter avoids copying the struct — use when `TValue` is a large value type (≥ 16 bytes).

    result: this in Result<TValue>
    The result to validate, passed by readonly reference.
    predicate: Func<TValue, bool>
    The condition to test on the success value.
    error: Error
    The error to return if the condition evaluates to `false`.

    Returns: The original result if valid or failed; otherwise, a failure with `error`.

    Type parameters: TValue: The source value type. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodEnsure<TValue>
    public static Result<TValue> Ensure<TValue>(this in Result<TValue> result, Func<TValue, bool> predicate, Func<Error> errorFactory)

    Validates the success value of `result` using `predicate`. Returns a failure produced by `errorFactory` if the predicate returns `false`. The error factory is only invoked when the predicate fails — avoids allocating `Error` on the success path. The `in` parameter avoids copying the struct — use when `TValue` is a large value type (≥ 16 bytes).

    result: this in Result<TValue>
    The result to validate, passed by readonly reference.
    predicate: Func<TValue, bool>
    The condition to test on the success value.
    errorFactory: Func<Error>
    A factory that generates the error if the condition evaluates to `false`.

    Returns: The original result if valid or failed; otherwise, a failure with the generated error.

    Type parameters: TValue: The source value type. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodEnsure<TValue>
    public static Result<TValue> Ensure<TValue>(this in Result<TValue> result, Func<TValue, bool> predicate, Func<TValue, Error> errorFactory)

    Validates the success value of `result` using `predicate`. Returns a failure produced by `errorFactory` (which receives the value) if the predicate returns `false`. Allows constructing context-aware errors (e.g. including the invalid value) without allocating on the success path. The `in` parameter avoids copying the struct — use when `TValue` is a large value type (≥ 16 bytes).

    result: this in Result<TValue>
    The result to validate, passed by readonly reference.
    predicate: Func<TValue, bool>
    The condition to test on the success value.
    errorFactory: Func<TValue, Error>
    A factory that receives the value and generates the error if the condition evaluates to `false`.

    Returns: The original result if valid or failed; otherwise, a failure with the generated error.

    Type parameters: TValue: The source value type. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodGetValueOrDefault<TValue>
    public static TValue GetValueOrDefault<TValue>(this in Result<TValue> result, TValue defaultValue)

    Returns the success value, or `defaultValue` if the result is not a success. The `in` parameter avoids copying the struct — use when `TValue` is a large value type (≥ 16 bytes).

    result: this in Result<TValue>
    The result to inspect, passed by readonly reference.
    defaultValue: TValue
    The fallback value to return if the result is not a success.

    Returns: The success value if successful; otherwise, `defaultValue`.

    Intentionally does NOT throw for an uninitialized `default(Result<TValue>)`. Per BCL `*OrDefault` convention (e.g., `Enumerable.FirstOrDefault`, `Dictionary.GetValueOrDefault`), methods suffixed with `OrDefault` return a fallback value rather than throw for any non-Success state. If you need to throw on Uninitialized, use `Match<TValue, TOut>(in Result<TValue>, Func<TValue, TOut>, Func<Error, TOut>)` instead. Type parameters: TValue: The source value type.

  • methodMap<TValue, TNext>
    public static Result<TNext> Map<TValue, TNext>(this in Result<TValue> result, Func<TValue, TNext> mapper)

    Maps the success value of `result` using `mapper`. The `in` parameter avoids copying the struct — use when `TValue` is a large value type (≥ 16 bytes).

    result: this in Result<TValue>
    The result to transform, passed by readonly reference.
    mapper: Func<TValue, TNext>
    The projection function applied to the success value.

    Returns: A new result with the mapped value on success, or the original error on failure.

    Type parameters: TValue: The source value type.; TNext: The projected output type. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodMap<TValue, TState, TNext>
    public static Result<TNext> Map<TValue, TState, TNext>(this in Result<TValue> result, TState state, Func<TState, TValue, TNext> mapper)

    Maps the success value of `result` using `mapper` with captured `state` to avoid closure allocation. The `in` parameter avoids copying the struct.

    result: this in Result<TValue>
    The result to transform, passed by readonly reference.
    state: TState
    The state value passed to the mapper function.
    mapper: Func<TState, TValue, TNext>
    The projection function applied to state and the success value.

    Returns: A new result with the mapped value on success, or the original error on failure.

    Type parameters: TValue: The source value type.; TState: The type of the state object passed to the mapper.; TNext: The projected output type. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodMatch<TValue, TOut>
    public static TOut Match<TValue, TOut>(this in Result<TValue> result, Func<TValue, TOut> onSuccess, Func<Error, TOut> onFailure)

    Evaluates `onSuccess` or `onFailure` based on the result state and returns the result of the chosen branch. The `in` parameter avoids copying the struct — use when `TValue` is a large value type (≥ 16 bytes).

    result: this in Result<TValue>
    The result to match on, passed by readonly reference.
    onSuccess: Func<TValue, TOut>
    The function to evaluate with the value if successful.
    onFailure: Func<Error, TOut>
    The function to evaluate with the error if failed.

    Returns: The value produced by the invoked branch.

    Type parameters: TValue: The source value type.; TOut: The output value type produced by the matching functions. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodMatch<TValue, TState, TOut>
    public static TOut Match<TValue, TState, TOut>(this in Result<TValue> result, TState state, Func<TState, TValue, TOut> onSuccess, Func<TState, Error, TOut> onFailure)

    Evaluates `onSuccess` or `onFailure` with captured `state` to avoid closure allocation. The `in` parameter avoids copying the struct.

    result: this in Result<TValue>
    The result to match on, passed by readonly reference.
    state: TState
    The state value passed to the matching delegates.
    onSuccess: Func<TState, TValue, TOut>
    The function to evaluate with state and value if successful.
    onFailure: Func<TState, Error, TOut>
    The function to evaluate with state and error if failed.

    Returns: The value produced by the invoked branch.

    Type parameters: TValue: The source value type.; TState: The type of the state object passed to the matching functions.; TOut: The output value type produced by the matching functions. Exceptions: InvalidOperationException: `result` is an uninitialized default value

  • methodTryGetValue<TValue>
    public static bool TryGetValue<TValue>(this in Result<TValue> result, out TValue value)

    Attempts to extract the success value without throwing. The `in` parameter avoids copying the struct — use when `TValue` is a large value type (≥ 16 bytes).

    result: this in Result<TValue>
    The result to inspect, passed by readonly reference.
    value: out TValue
    When this method returns `true`, contains the success value.

    Returns: `true` if the result is a success; otherwise `false`.

    Never throws per BCL `Try*` convention — returns `false` and sets `value` to `default!` for both Failure and Uninitialized states. Use `Match<TValue, TOut>(in Result<TValue>, Func<TValue, TOut>, Func<Error, TOut>)` if you need to distinguish Failure from Uninitialized and want an exception for the latter. Type parameters: TValue: The source value type.

struct

Result<TValue>

Assembly: EricksonLopez.Result
public readonly partial struct Result<TValue> : IResultOutcome, IResultFactory<Result<TValue>>, IEquatable<Result<TValue>>
Implements: IEquatable<Result<TValue>>, IResultFactory<Result<TValue>>, IResultOutcome

Represents the result of an operation that returns a value of type `TValue`. The state can be either Success (containing the value) or Failure (containing an `Error`).

Remarks:

Performance Note: Because this is a `readonly struct`, the entire struct is copied by value when passed around. If `TValue` is a large value type (like a large struct or tuple), this can incur significant copy overhead during method calls or when chaining methods. Type parameters: TValue: The type of the successful value.

Members (57)

  • methodBind
    public Result Bind(Func<TValue, Result> bind)

    Chains a non-generic operation if this result is successful.

    bind: Func<TValue, Result>
    The operation to execute with the success value.

    Returns: The non-generic result of executing `bind` on success; otherwise, a failure with the original error.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodBind<TNext>
    public Result<TNext> Bind<TNext>(Func<TValue, Result<TNext>> bind)

    Chains another generic operation if this result is successful.

    bind: Func<TValue, Result<TNext>>
    The operation to execute with the success value.

    Returns: The result of executing `bind` on success; otherwise, a typed failure with the original error.

    Type parameters: TNext: The value type of the chained result. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodBind<TState, TNext>
    public Result<TNext> Bind<TState, TNext>(TState state, Func<TState, TValue, Result<TNext>> bind)

    Chains another generic operation using captured state if this result is successful.

    state: TState
    The state value passed to the bind function.
    bind: Func<TState, TValue, Result<TNext>>
    The operation to execute with state and the success value.

    Returns: The result of executing `bind` on success; otherwise, a typed failure with the original error.

    Type parameters: TState: The type of the state object passed to the bind function.; TNext: The value type of the chained result. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodBind<TState>
    public Result Bind<TState>(TState state, Func<TState, TValue, Result> bind)

    Chains a non-generic operation using captured state if this result is successful.

    state: TState
    The state value passed to the bind function.
    bind: Func<TState, TValue, Result>
    The operation to execute with state and the success value.

    Returns: The non-generic result of executing `bind` on success; otherwise, a failure with the original error.

    Type parameters: TState: The type of the state object passed to the bind function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodCreateFailure
    public static Result<TValue> CreateFailure(Error error)

    Creates a failed instance of `TSelf` containing the specified `error`.

    error: Error
    The error describing why the operation failed.

    Returns: A failed `TSelf` instance.

  • methodDeconstruct
    public void Deconstruct(out bool isSuccess, out Error? error)

    Deconstructs the result into success flag and error, ignoring the value. Useful when the value is not needed.

    isSuccess: out bool
    When this method returns, contains `true` if the result succeeded; otherwise, `false`.
    error: out Error?
    When this method returns, contains the associated `Error` if failed; otherwise, `null`.
  • methodDeconstruct
    public void Deconstruct(out bool isSuccess, out TValue? value, out Error? error)

    Deconstructs the result into its success state, value, and optional error.

    isSuccess: out bool
    When this method returns, contains `true` if the result succeeded; otherwise, `false`.
    value: out TValue?
    When this method returns, contains the success value if successful; otherwise, the default value for `TValue`.
    error: out Error?
    When this method returns, contains the associated `Error` if failed; otherwise, `null`.
  • methodDiscardValue
    public Result DiscardValue()

    Discards the typed value and returns a non-generic `Result`. Preserves success or failure state and any associated `Error`.

    Returns: A non-generic `Result` with equivalent success or failure state.

    Use this when you need to pass a result to a method that accepts a non-generic `Result`, for example when aggregating results with `Result.Combine(ReadOnlySpan<Result>)`. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure
    public Result<TValue> Ensure(Func<TValue, bool> predicate, Error error)

    Validates that the success value satisfies the specified predicate.

    predicate: Func<TValue, bool>
    The condition to test on the success value.
    error: Error
    The error to return if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with `error`.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure
    public Result<TValue> Ensure(Func<TValue, bool> predicate, Func<Error> errorFactory)

    Validates a successful result using `predicate`, constructing the error lazily via `errorFactory` only when the predicate fails.

    predicate: Func<TValue, bool>
    The condition to test on the success value.
    errorFactory: Func<Error>
    A factory that generates the error if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with the generated error.

    Prefer this overload over `Ensure(Func<TValue, bool>, Error)` when error construction is expensive (e.g., captures `Activity.Current`, allocates metadata, or involves string formatting). The error factory is never invoked on the success path. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure
    public Result<TValue> Ensure(Func<TValue, bool> predicate, Func<TValue, Error> errorFactory)

    Validates a successful result using `predicate`, constructing the error lazily via `errorFactory` only when the predicate fails. The error factory receives the current value to allow contextual error messages.

    predicate: Func<TValue, bool>
    The condition to test on the success value.
    errorFactory: Func<TValue, Error>
    A factory that receives the value and generates the error if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with the generated error.

    Use this overload when the error message depends on the value, for example:

    result.Ensure(
        order => order.Total > 0,
        order => Error.Validation("Order.InvalidTotal", $"Order {order.Id} has invalid total {order.Total}"));

    For error construction that does not need the value, use `Ensure(Func<TValue, bool>, Func<Error>)` instead. 💡 Allocation tip: Use `Ensure<TState>(TState, Func<TState, TValue, bool>, Func<TState, TValue, Error>)` to pass external context without a closure. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure<TState>
    public Result<TValue> Ensure<TState>(TState state, Func<TState, TValue, bool> predicate, Error error)

    Validates that the success value satisfies the specified predicate using captured state.

    state: TState
    The state value passed to the predicate.
    predicate: Func<TState, TValue, bool>
    The condition to test on state and the success value.
    error: Error
    The error to return if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with `error`.

    Type parameters: TState: The type of the state object passed to the predicate. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure<TState>
    public Result<TValue> Ensure<TState>(TState state, Func<TState, TValue, bool> predicate, Func<Error> errorFactory)

    Validates a successful result using `predicate` with captured state, constructing the error lazily via `errorFactory` only when the predicate fails.

    state: TState
    The state value passed to the predicate.
    predicate: Func<TState, TValue, bool>
    The condition to test on state and the success value.
    errorFactory: Func<Error>
    A factory that generates the error if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with the generated error.

    Type parameters: TState: The type of the state object passed to the predicate. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEnsure<TState>
    public Result<TValue> Ensure<TState>(TState state, Func<TState, TValue, bool> predicate, Func<TState, TValue, Error> errorFactory)

    Validates a successful result using `predicate` with captured state, constructing the error lazily via `errorFactory` only when the predicate fails. The error factory receives both the state and the current value.

    state: TState
    The state value passed to the predicate and error factory.
    predicate: Func<TState, TValue, bool>
    The condition to test on state and the success value.
    errorFactory: Func<TState, TValue, Error>
    A factory that receives state and value to generate the error if the condition evaluates to `false`.

    Returns: The current result if the condition is met or if the result is already a failure; otherwise, a failure with the generated error.

    Type parameters: TState: The type of the state object passed to the predicate and error factory. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodEquals
    public bool Equals(in Result<TValue> other)

    Determines whether this result is equal to another result by comparing state, error (when both are failures), and value (when both are successes).

    other: in Result<TValue>
    The other result to compare against, passed by readonly reference.

    Returns: `true` if both results represent the same outcome; otherwise, `false`.

    The parameter is passed by reference (`in`) to avoid copying the struct, which is important for large value types such as `Result<decimal>` or `Result<(T1, T2, T3)>`.

  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodExecute
    public void Execute(Action<TValue> onSuccess, Action<Error> onFailure)

    Invokes `onSuccess` with the value when successful, or `onFailure` with the error when failed — without returning a value.

    onSuccess: Action<TValue>
    The action to invoke with the value on success.
    onFailure: Action<Error>
    The action to invoke with the error on failure.

    `Execute` is the void side-effect counterpart to `Match<TOut>`: use `Match` when you need a return value, and `Execute` for pure side-effects (logging, dispatching events, updating state). Naming note: The name `Execute` is borrowed from functional programming. See `Result.Execute(Action, Action<Error>)` for the full rationale. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodExecute<TState>
    public void Execute<TState>(TState state, Action<TState, TValue> onSuccess, Action<TState, Error> onFailure)

    Invokes `onSuccess` or `onFailure` for their side-effects, forwarding `state` to avoid a closure allocation.

    state: TState
    The state value passed to the actions.
    onSuccess: Action<TState, TValue>
    The action to invoke with state and value on success.
    onFailure: Action<TState, Error>
    The action to invoke with state and error on failure.

    Use this overload in hot paths where capturing variables in a closure would cause heap allocation. Type parameters: TState: The type of the state object passed to the actions. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodFailure
    public static Result<TValue> Failure(Error error)

    Creates a new failed `Result<TValue>` with the specified error.

    error: Error
    The error describing the failure.

    Returns: A failed `Result<TValue>` containing `error`.

    Exceptions: ArgumentNullException: `error` is `null`

  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodGetValueOrDefault
    public TValue GetValueOrDefault(TValue defaultValue)

    Returns the success value if successful; otherwise, returns the specified default value.

    defaultValue: TValue
    The fallback value to return if the result is a failure or uninitialized.

    Returns: The success value if successful; otherwise, `defaultValue`.

    Returns `defaultValue` for failure and uninitialized states. Never throws, consistent with the BCL convention for `*OrDefault` methods (e.g., `Nullable<T>.GetValueOrDefault()`, `Dictionary.TryGetValue`). Use `GetValueOrFallback(Func<Error, TValue>)` if you need to distinguish failure from uninitialized, or if you need access to the error to produce the fallback.

  • methodGetValueOrFallback
    public TValue GetValueOrFallback(Func<Error, TValue> fallback)

    Returns the success value, or invokes `fallback` with the error to produce a default. Named `GetValueOrFallback` (not an overload of `GetValueOrDefault`) to avoid ambiguity when `TValue` is itself a delegate type.

    fallback: Func<Error, TValue>
    The function generating a fallback value from the failure `Error`.

    Returns: The success value if successful; otherwise, the fallback value produced by `fallback`.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodGetValueOrFallback<TState>
    public TValue GetValueOrFallback<TState>(TState state, Func<TState, Error, TValue> fallback)

    Returns the success value, or invokes `fallback` with captured state and error to produce a default value.

    state: TState
    The state value passed to the fallback function.
    fallback: Func<TState, Error, TValue>
    The function generating a fallback value from state and the failure `Error`.

    Returns: The success value if successful; otherwise, the fallback value produced by `fallback`.

    Type parameters: TState: The type of the state object passed to the fallback function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodInspect
    public Result<TValue> Inspect(Action<Result<TValue>> action)

    Executes the specified action unconditionally with the current result, then returns this result unchanged.

    action: Action<Result<TValue>>
    The action to execute with this result.

    Returns: The current result instance unchanged.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodInspect<TState>
    public Result<TValue> Inspect<TState>(TState state, Action<TState, Result<TValue>> action)

    Executes the specified action unconditionally with captured state and the current result, then returns this result unchanged.

    state: TState
    The state value passed to the action.
    action: Action<TState, Result<TValue>>
    The action to execute with state and this result.

    Returns: The current result instance unchanged.

    Type parameters: TState: The type of the state object passed to the action. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMap<TNext>
    public Result<TNext> Map<TNext>(Func<TValue, TNext> mapper)

    Transforms the success value using the specified mapper function.

    mapper: Func<TValue, TNext>
    The mapping function applied to the success value.

    Returns: A new `Result<TNext>` containing the mapped value on success, or the original error on failure.

    Type parameters: TNext: The return type of the mapper function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMap<TState, TNext>
    public Result<TNext> Map<TState, TNext>(TState state, Func<TState, TValue, TNext> mapper)

    Transforms the success value using the specified mapper function and captured state.

    state: TState
    The state value passed to the mapper function.
    mapper: Func<TState, TValue, TNext>
    The mapping function applied to the state and success value.

    Returns: A new `Result<TNext>` containing the mapped value on success, or the original error on failure.

    Type parameters: TState: The type of the state object passed to the mapper function.; TNext: The return type of the mapper function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMapError
    public Result<TValue> MapError(Func<Error, Error> mapper)

    Transforms the error of a failed result using the provided `mapper`. Returns the same success result unchanged.

    mapper: Func<Error, Error>
    The function used to map the error if this result is a failure.

    Returns: A new failed result with the transformed error, or the current success result unchanged.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMapError<TState>
    public Result<TValue> MapError<TState>(TState state, Func<TState, Error, Error> mapper)

    Transforms the error of a failed result using the provided `mapper` and captured state. Returns the same success result unchanged.

    state: TState
    The state value passed to the mapper function.
    mapper: Func<TState, Error, Error>
    The function used to map the error if this result is a failure.

    Returns: A new failed result with the transformed error, or the current success result unchanged.

    Type parameters: TState: The type of the state object passed to the mapper function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMapFailure<TOut>
    public TOut MapFailure<TOut>(Func<Error, TOut> onFailure, TOut successDefault)

    Maps a failure `Error` to a value of type `TOut`, or returns `successDefault` when this result is successful.

    onFailure: Func<Error, TOut>
    A function that produces a `TOut` from the `Error`.
    successDefault: TOut
    The value to return when the result is successful.

    Returns: The result of invoking `onFailure` on failure, or `successDefault` on success.

    Use this when you only need to handle the failure branch without mapping the success value. For transforming both branches, use `Match<TOut>(Func<TValue, TOut>, Func<Error, TOut>)`. 💡 Allocation tip: If `onFailure` captures variables from an outer scope, use `MapFailure<TState, TOut>(TState, Func<TState, Error, TOut>, TOut)` to pass the captured values as a `TState` parameter and avoid closure allocation. Type parameters: TOut: The output type of the transformation. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMapFailure<TState, TOut>
    public TOut MapFailure<TState, TOut>(TState state, Func<TState, Error, TOut> onFailure, TOut successDefault)

    Maps a failure `Error` to a value of type `TOut` using captured `state` to avoid closure allocation. Returns `successDefault` when this result is successful.

    state: TState
    The state value passed to the failure mapping function.
    onFailure: Func<TState, Error, TOut>
    A function that produces a `TOut` from state and the `Error`.
    successDefault: TOut
    The value to return when the result is successful.

    Returns: The result of invoking `onFailure` on failure, or `successDefault` on success.

    Type parameters: TState: The type of the state object passed to the mapper function.; TOut: The output type of the transformation. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMatch<TOut>
    public TOut Match<TOut>(Func<TValue, TOut> onSuccess, Func<Error, TOut> onFailure)

    Evaluates the corresponding branch depending on whether the result is a success or failure.

    onSuccess: Func<TValue, TOut>
    The function to evaluate with the value if the result is successful.
    onFailure: Func<Error, TOut>
    The function to evaluate with the `Error` if the result is a failure.

    Returns: The value produced by either `onSuccess` or `onFailure`.

    Type parameters: TOut: The output type produced by the matching functions. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodMatch<TState, TOut>
    public TOut Match<TState, TOut>(TState state, Func<TState, TValue, TOut> onSuccess, Func<TState, Error, TOut> onFailure)

    Evaluates the corresponding branch using captured state to avoid closure allocations.

    state: TState
    The state value passed to the matching delegates.
    onSuccess: Func<TState, TValue, TOut>
    The function to evaluate with state and value if the result is successful.
    onFailure: Func<TState, Error, TOut>
    The function to evaluate with state and `Error` if the result is a failure.

    Returns: The value produced by either `onSuccess` or `onFailure`.

    Type parameters: TState: The type of the state object passed to the matching functions.; TOut: The output type produced by the matching functions. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodRecover
    public Result<TValue> Recover(Func<Error, Result<TValue>> recovery)

    If this result is a failure, invokes `recovery` to attempt a corrective result.

    recovery: Func<Error, Result<TValue>>
    The recovery function producing a corrective typed result from the failure `Error`.

    Returns: The recovery result if this instance is a failure; otherwise, this instance unchanged.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodRecover<TState>
    public Result<TValue> Recover<TState>(TState state, Func<TState, Error, Result<TValue>> recovery)

    If this result is a failure, invokes `recovery` with captured state to attempt a corrective result.

    state: TState
    The state value passed to the recovery function.
    recovery: Func<TState, Error, Result<TValue>>
    The recovery function producing a corrective typed result from state and the failure `Error`.

    Returns: The recovery result if this instance is a failure; otherwise, this instance unchanged.

    Type parameters: TState: The type of the state object passed to the recovery function. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodSuccess
    public static Result<TValue> Success(TValue value)

    Creates a success result wrapping `value`.

    value: TValue
    The value to wrap in a successful result.

    Returns: A new successful `Result<TValue>` instance containing `value`.

    Null values: If `TValue` is a nullable reference type (e.g., `Result<string?>`), `null` is a valid success value and will not throw. The .NET nullable type system provides compile-time protection for non-nullable reference types; no runtime `null` check is applied. For value types, `null` is prevented at compile time by the type system.

  • methodTap
    public Result<TValue> Tap(Action<TValue> action)

    Executes `action` if this result is successful, then returns this result unchanged.

    action: Action<TValue>
    The action to execute if the result is successful.

    Returns: The current result instance unchanged.

    Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTap<TState>
    public Result<TValue> Tap<TState>(TState state, Action<TState, TValue> action)

    Executes `action` with captured state if this result is successful, then returns this result unchanged.

    state: TState
    The state value passed to the action.
    action: Action<TState, TValue>
    The action to execute if the result is successful.

    Returns: The current result instance unchanged.

    Type parameters: TState: The type of the state object passed to the action. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTapOnFailure
    public Result<TValue> TapOnFailure(Action<Error> action)

    Executes `action` if this result is a failure, then returns this result unchanged.

    action: Action<Error>
    The action to execute with the `Error` if the result is a failure.

    Returns: The current result instance unchanged.

    Executes the action only on failure; symmetric with `TapOnSuccess(Action<TValue>)`. 💡 Allocation tip: Use `TapOnFailure<TState>(TState, Action<TState, Error>)` to avoid closure allocations when capturing outer variables. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTapOnFailure<TState>
    public Result<TValue> TapOnFailure<TState>(TState state, Action<TState, Error> action)

    Executes `action` with captured state if this result is a failure, then returns this result unchanged.

    state: TState
    The state value passed to the action.
    action: Action<TState, Error>
    The action to execute with state and the error if the result is a failure.

    Returns: The current result instance unchanged.

    💡 Allocation tip: This overload passes context via `state` instead of a captured closure. Type parameters: TState: The type of the state object passed to the action. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTapOnSuccess
    public Result<TValue> TapOnSuccess(Action<TValue> action)

    Executes `action` if this result is successful, then returns this result unchanged.

    action: Action<TValue>
    The action to execute with the success value.

    Returns: The current result instance unchanged.

    Executes the action only on success; symmetric with `TapOnFailure(Action<Error>)`. Use `Inspect(Action<Result<TValue>>)` for unconditional execution (both success and failure). 💡 Allocation tip: Use `TapOnSuccess<TState>(TState, Action<TState, TValue>)` to avoid closure allocations when capturing outer variables. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodTapOnSuccess<TState>
    public Result<TValue> TapOnSuccess<TState>(TState state, Action<TState, TValue> action)

    Executes `action` with captured state if this result is successful, then returns this result unchanged.

    state: TState
    The state value passed to the action.
    action: Action<TState, TValue>
    The action to execute with state and the success value.

    Returns: The current result instance unchanged.

    💡 Allocation tip: This overload passes context via `state` instead of a captured closure. Type parameters: TState: The type of the state object passed to the action. Exceptions: InvalidOperationException: The result is an uninitialized default value

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTryGetError
    public bool TryGetError(out Error error)

    Attempts to get the error if this result is a failure. Returns `false` for both `IsSuccess` and uninitialized default results.

    error: out Error
    The error, or `null` if the result is not a failure.

    Returns: `true` if this result is a failure and `error` has been set; `false` for both successful results and uninitialized default results.

    ⚠ Uninitialized results: This overload returns `false` silently for `default(Result<TValue>)` without indicating that the result is in an invalid state. If you need to distinguish between Success and Uninitialized, use `TryGetError(out Error, out bool)` which provides an `isUninitialized` output. Always construct results via `Result.Success<TValue>(TValue)` or `Result.Failure<TValue>(Error)`.

  • methodTryGetError
    public bool TryGetError(out Error error, out bool isUninitialized)

    Attempts to retrieve the error, distinguishing between failure and uninitialized states.

    error: out Error
    When this method returns, contains the associated `Error` if the result is a failure; otherwise, `null`.
    isUninitialized: out bool
    When this method returns, contains `true` if the result is an uninitialized default value; otherwise, `false`.

    Returns: `true` if the result is a failure and `error` is populated; otherwise, `false`.

  • methodTryGetValue
    public bool TryGetValue(out TValue value)

    Attempts to get the success value if this result is successful. Returns `false` for both `IsFailure` and uninitialized default results.

    value: out TValue
    The success value, or `default` if the result is not successful.

    Returns: `true` if this result is successful and `value` has been set; `false` for both failed results and uninitialized default results.

    ⚠ Uninitialized results: This overload returns `false` silently for `default(Result<TValue>)` — indistinguishable from a failure result. If you need to distinguish between Failure and Uninitialized, use `TryGetValue(out TValue, out bool)` which provides an `isUninitialized` output. Always construct results via `Result.Success<TValue>(TValue)` or `Result.Failure<TValue>(Error)`.

  • methodTryGetValue
    public bool TryGetValue(out TValue value, out bool isUninitialized)

    Attempts to get the success value, distinguishing between Success, Failure, and Uninitialized states.

    value: out TValue
    The success value, or `default` if not successful.
    isUninitialized: out bool
    `true` if this result is an uninitialized default value; `false` for properly constructed results (either success or failure).

    Returns: `true` if this result is successful and `value` has been set; `false` if the result is a failure or uninitialized.

    Use this overload when you need to distinguish between a legitimate failure and an accidental `default(Result<TValue>)`. This mirrors the `TryGetError(out Error, out bool)` pattern already available on the failure path.

  • methodimplicit operator Result
    public static implicit operator Result(in Result<TValue> result)

    Converts a typed `Result<TValue>` implicitly to a non-generic `Result`, preserving the outcome state and error while discarding the typed value.

    result: in Result<TValue>
    The typed result to convert.
  • methodimplicit operator Result<TValue>
    public static implicit operator Result<TValue>(Error error)

    Converts an `Error` implicitly into a failed `Result<TValue>`.

    error: Error
    The error to wrap in a failed result.
  • methodimplicit operator Result<TValue>
    public static implicit operator Result<TValue>(TValue value)

    Converts a value implicitly into a successful `Result<TValue>`.

    value: TValue
    The value to wrap in a successful result.
  • methodoperator !=
    public static bool operator !=(in Result<TValue> left, in Result<TValue> right)

    Determines whether two `Result<TValue>` instances are not equal.

    left: in Result<TValue>
    The first result to compare.
    right: in Result<TValue>
    The second result to compare.

    Returns: `true` if the instances are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(in Result<TValue> left, in Result<TValue> right)

    Determines whether two `Result<TValue>` instances are equal.

    left: in Result<TValue>
    The first result to compare.
    right: in Result<TValue>
    The second result to compare.

    Returns: `true` if both instances are equal; otherwise, `false`.

  • propertyError
    public Error Error { get; }

    Gets the error associated with this result.

    Exceptions: InvalidOperationException: The result is successful

  • propertyIsFailure
    public bool IsFailure { get; }

    Gets a value indicating whether the operation failed.

    ⚠ Uninitialized default: Returns `false` for an uninitialized `default(Result<TValue>)` — the same as a success (neither `true` nor `false` corresponds to the uninitialized state). Use `IsUninitialized` to distinguish.

  • propertyIsSuccess
    public bool IsSuccess { get; }

    Gets a value indicating whether the operation succeeded.

    ⚠ Uninitialized default: Returns `false` for an uninitialized `default(Result<TValue>)` — the same as a failure, but without an error. Always construct results via `Result.Success<TValue>(TValue)` or `Result.Failure<TValue>(Error)`. Use `IsUninitialized` to detect an uninitialized default explicitly.

  • propertyIsUninitialized
    public bool IsUninitialized { get; }

    Gets a value indicating whether the struct is an uninitialized default value.

  • propertyValue
    public TValue Value { get; }

    Gets the success value.

    Exceptions: InvalidOperationException: The result is a failure or uninitialized default value

class

WellKnownErrors

Assembly: EricksonLopez.Result
public static class WellKnownErrors

Provides well-known error codes and system error constants used by the Result framework.

Members (2)

  • fieldCombinedFailuresCode
    public const string CombinedFailuresCode

    Gets the error code used when multiple results are combined and one or more failures occur.

  • fieldUninitializedError
    public static readonly Error UninitializedError

    Gets the error instance used when an uninitialized result is accessed.

    Uses `Error.CreateSentinel` to avoid capturing `Activity.Current` at static initialization time, and to ensure `Error.TraceId` serializes as `null` rather than an empty string.

EricksonLopez.Result.Analyzers#

18
class

BoolOperatorUsageAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class BoolOperatorUsageAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer (RESULT013) that warns when `Result` or `Result<T>` is used directly in a condition context (e.g. `if (result)`, `result ? a : b`, `while (result)`).

Remarks:

An uninitialized `Result` struct (`default(Result)`) has a state value of 0 (`Uninitialized`). Its `operator true` returns `false` without throwing, causing uninitialized results to silently evaluate as failure in boolean conditions. Explicitly checking `.IsSuccess` or `.IsFailure` avoids this ambiguity and makes the intention explicit.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

BoolOperatorUsageCodeFix

Assembly: EricksonLopez.Result.Analyzers
public sealed class BoolOperatorUsageCodeFix : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix provider for `RESULT013` — Avoid implicit bool conversion of Result in condition contexts.

Remarks:

Rewrites conditions using `result` to explicit checks:

// Before (RESULT013)
if (result)

// After
if (result.IsSuccess)

Members (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

ClosureCaptureAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class ClosureCaptureAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer that warns when lambda arguments to `Result.Map()`, `Result.Bind()`, `Result.TapOnSuccess()`, `Result.TapOnFailure()`, `Result.Ensure()`, `Result.MapError()`, `Result.MapFailure()`, `Result.Execute()`, or `Result.Inspect()` capture local variables or `this` from the enclosing method, causing a heap-allocated closure.

Remarks:

Rule RESULT004: "Lambda in {MethodName}() captures {CaptureCount} local variable(s) ({VariableNames}): use the {MethodName}(TState, ...) overload to avoid the allocation." `Result`/`Result<T>` provides `TState` overloads for all monadic methods (Map, Bind, TapOnSuccess, TapOnFailure, Ensure, MapError, Inspect) that allow the caller to pass captured state as a parameter instead of creating a heap-allocated closure delegate. When a lambda in a hot path captures local variables or `this`, this allocates a new closure object on every call. Example — closure allocation (warned):

var userId = GetUserId();
return result.Map(x => new Dto(userId, x)); // allocates closure capturing userId

// Also warned — capturing `this`:
return result.Map(x => this.ProcessOrder(x)); // allocates closure capturing this

Recommended — zero closure allocation:

var userId = GetUserId();
return result.Map(userId, (uid, x) => new Dto(uid, x)); // no closure

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

ClosureCaptureCodeFix

Assembly: EricksonLopez.Result.Analyzers
public sealed class ClosureCaptureCodeFix : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix provider for `RESULT004` — Closure capture in Result pipeline methods.

Members (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

DefaultResultBooleanConditionAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class DefaultResultBooleanConditionAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer (RESULT014) that warns when an uninitialized `Result` (e.g., `default(Result)`, `new Result()`, or an uninitialized local/private field) is evaluated in a boolean condition.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

DefaultResultReturnAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class DefaultResultReturnAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer (RESULT012) that warns when `default` or `default(Result)` is returned from a method returning `Result` or `Result<T>`.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

DefaultResultReturnCodeFix

Assembly: EricksonLopez.Result.Analyzers
public sealed class DefaultResultReturnCodeFix : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix provider for `RESULT012` — Avoid returning default(Result) or default(Result<T>).

Remarks:

Rewrites default returns to explicit `Result.Success(...)` or `Result.Failure(...)` expressions:

// Before (RESULT012)
return default;

// After
return Result.Success();

Members (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

EndpointFilterOpenApiAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class EndpointFilterOpenApiAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer that warns when `AddResultEndpointFilter()` is called without a corresponding `.Produces<T>()` call in the fluent chain.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

ErrorBuilderDiscardedReturnAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class ErrorBuilderDiscardedReturnAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer that warns when the return value of `ErrorBuilder.With*()` methods is discarded.

Remarks:

Rule RESULT003: "Return value of ErrorBuilder.{MethodName}() is discarded. ErrorBuilder is a struct; the mutated copy is lost. Assign the result or chain the call." `ErrorBuilder` is a `readonly struct` with copy-on-write semantics. Its `With*()` methods return a new copy with the requested change applied; they do NOT mutate the original builder. When the return value is discarded (e.g., standalone statement), the new copy (with the change) is silently lost, leading to bugs:

var builder = Error.Create("code", "desc");
builder.WithType(ErrorType.Domain);  // ⚠ return value discarded — mutation lost
var error = builder.Build();          // type is still Failure, not Domain

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

ErrorBuilderDiscardedReturnCodeFix

Assembly: EricksonLopez.Result.Analyzers
public sealed class ErrorBuilderDiscardedReturnCodeFix : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix provider for `RESULT003` — ErrorBuilder discarded return value.

Remarks:

When the return value of `ErrorBuilder.With*()` is discarded (a standalone expression statement), this fix rewrites the statement to reassign the result back to the local variable that holds the builder:

// Before (RESULT003 — discarded return value)
builder.WithType(ErrorType.Domain);

// After (CodeFix applied)
builder = builder.WithType(ErrorType.Domain);

The fix also handles the case where the invocation is on a property accessor or method return — in those cases the fix suggests introducing a local variable:

// Before
GetBuilder().WithType(ErrorType.Domain);

// After
var builder = GetBuilder().WithType(ErrorType.Domain);

Scope: This fix operates on a single document and does not perform solution-wide renames or refactors.

Members (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

HashSetErrorEqualityAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class HashSetErrorEqualityAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Reports diagnostics when `Error` collections or LINQ operations omit an explicit equality comparer.

Remarks:

Warns when: - `HashSet<Error>` or `Dictionary<Error, TValue>` is instantiated without `ErrorEqualityComparer.Strict` (or `ErrorEqualityComparer.Default` if intentional). - LINQ `Enumerable.Distinct()`, `Enumerable.ToHashSet()` is called without `ErrorEqualityComparer.Strict` on an `IEnumerable<Error>`. - LINQ `Enumerable.DistinctBy()`, `Enumerable.GroupBy()` use `Error` as the source type without an explicit strict comparer. Root cause: `Error.Equals(Error?)` performs a shallow equality check on 5 semantic fields (`Code`, `Description`, `Type`, `Severity`, `Retryability`). Fields like `TraceId`, `CorrelationId`, and `Metadata` are intentionally excluded because they vary per request. This means that when two errors share the same semantic fields but differ in `TraceId` or `Metadata`, any collection or LINQ operation using the default comparer will silently deduplicate them - losing one of the errors. Fix: Use `ErrorEqualityComparer.Strict` to include all fields in equality checks, or use `ErrorEqualityComparer.Default` if semantic deduplication is intentional.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

HashSetErrorEqualityCodeFix

Assembly: EricksonLopez.Result.Analyzers
public sealed class HashSetErrorEqualityCodeFix : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix provider for `RESULT007` — Missing ErrorEqualityComparer.Strict in collection or LINQ deduplication.

Remarks:

Adds an explicit `ErrorEqualityComparer.Strict` (or `ErrorEqualityComparer.Default`) argument to collection instantiations or LINQ deduplication calls.

Members (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

IncludeDescriptionSecurityAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class IncludeDescriptionSecurityAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer (RESULT009) that warns when `ResultHttpOptions.IncludeDescription` is set directly to `true` without an environment guard, which may expose internal error descriptions (including exception messages, file paths, or PII) in HTTP ProblemDetails responses in production environments.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

InnerErrorChainingAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class InnerErrorChainingAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer that warns when `ErrorBuilder.WithInnerError(Error)` is chained 2 or more times consecutively, causing O(n\u00b2) ImmutableArray copying.

Remarks:

Rule RESULT006: "Chained ErrorBuilder.WithInnerError() calls are O(n\u00b2). Use WithInnerErrors(IEnumerable<Error>) to add multiple inner errors efficiently." `ErrorBuilder` is a `readonly struct` with copy-on-write semantics. Each call to `WithInnerError(Error)` creates a new `ImmutableArray<Error>` with one additional element (O(n) copy per call). Chaining N calls is O(n\u00b2) total.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

LargeResultValueAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class LargeResultValueAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer that warns when `Result<T>` is used with a struct type whose estimated size exceeds 64 bytes. Large structs cause excessive copying on every pipeline operation (Map, Bind, Tap, etc.) because `Result<T>` is a readonly struct that copies by value.

Remarks:

Rule RESULT001: "Result<T> with T = '{TypeName}' (estimated {Size} bytes). Consider using a class or wrapping in a class to avoid excessive struct copying in Result pipeline operations."

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

MetadataChainingAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class MetadataChainingAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer that warns when `Error.WithMetadata(string, object)` or `ErrorBuilder.WithMetadata(string, object?)` is chained 3 or more times consecutively, creating multiple intermediate allocations.

Remarks:

Rule RESULT005 covers two related patterns: - Error.WithMetadata chaining: Each call creates a new `Error` heap object. Chaining 3+ calls allocates N intermediate `Error` instances that are immediately discarded. - ErrorBuilder.WithMetadata chaining: Each single-key call performs an O(log k) AVL-tree mutation on the backing `ImmutableDictionary`, creating N intermediate dictionary nodes. Using the batch overload `WithMetadata(IEnumerable{KeyValuePair{string, object}})` or `WithMetadata(IReadOnlyDictionary{string, object?})` applies all entries with a single `AddRange` call. Example for Error (3+ chained calls warned):

var error = Error.NotFound("code", "desc")
    .WithMetadata("a", 1)
    .WithMetadata("b", 2)
    .WithMetadata("c", 3); // 3 intermediate Error copies created and discarded

Recommended -- single allocation:

var error = Error.NotFound("code", "desc")
    .WithMetadata(new Dictionary{string, object?} { ["a"] = 1, ["b"] = 2, ["c"] = 3 });

Example for ErrorBuilder (3+ chained calls warned):

var error = Error.Create("code", "desc")
    .WithMetadata("a", 1)   // each call mutates ImmutableDictionary independently
    .WithMetadata("b", 2)
    .WithMetadata("c", 3)
    .Build();

Recommended -- single batch call:

var error = Error.Create("code", "desc")
    .WithMetadata(new Dictionary{string, object?} { ["a"] = 1, ["b"] = 2, ["c"] = 3 })
    .Build();

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

ResultExceptionBehaviorMessageAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class ResultExceptionBehaviorMessageAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer (RESULT010) that warns when `ex.Message` is used inside the errorFactory delegate for `AddResultExceptionBehavior`.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

class

TraceOutcomeWithoutMetricsAnalyzer

Assembly: EricksonLopez.Result.Analyzers
public sealed class TraceOutcomeWithoutMetricsAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Represents a Roslyn diagnostic analyzer (RESULT_OTEL_001) that reports an informational hint when `TraceOutcome`, `TraceOnFailure`, or `TraceOnSuccess` are called without the optional `metrics` parameter, meaning no `ResultMetrics` instance will record metrics for this trace call.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier for this analyzer rule.

EricksonLopez.Result.AspNetCore#

9
class

AspNetCoreJsonSerializerContext

Assembly: EricksonLopez.Result.AspNetCore
public sealed partial class AspNetCoreJsonSerializerContext : JsonSerializerContext
Inherits: JsonSerializerContext

Source generator context for NativeAOT-compatible JSON serialization of RFC 9457 `ProblemDetails` responses and `ErrorDetailDto` extension payloads.

Members (0)

This type declares 0 public members (e.g. marker interface or empty enum/record).

record

ErrorDetailDto

Assembly: EricksonLopez.Result.AspNetCore
public readonly record struct ErrorDetailDto(string Code, string Description, string Type, string Severity, string Retryability, string? DescriptionKey, string? TraceId)

Represents an error detail for ProblemDetails payload (NativeAOT compliant). Enum values are serialized as stable string constants to avoid naming instability across versions.

Remarks:

Registered in `AspNetCoreJsonSerializerContext` for AOT-safe serialization. It is used internally to populate the `errors` array in RFC 9457 ProblemDetails extensions. Properties: - `Code` — application error code (e.g., `"ORDER.EXPIRED"`). - `Description` — human-readable error message. - `Type` — `ErrorType` as a PascalCase string (e.g., `"Validation"`). - `Severity` — `ErrorSeverity` as a PascalCase string (e.g., `"Error"`). - `Retryability` — `ErrorRetryability` as a PascalCase string (e.g., `"Transient"`). - `DescriptionKey` — optional localization key, or `null` if not set. - `TraceId` — optional OpenTelemetry trace ID, or `null` if not set.

Members (8)

  • constructorErrorDetailDto
    public ErrorDetailDto(string Code, string Description, string Type, string Severity, string Retryability, string? DescriptionKey, string? TraceId)

    Initializes a new instance of ErrorDetailDto.

    Code: string
    The application-specific error code.
    Description: string
    The human-readable description of the error.
    Type: string
    The string representation of the `ErrorType`.
    Severity: string
    The string representation of the `ErrorSeverity`.
    Retryability: string
    The string representation of the `ErrorRetryability`.
    DescriptionKey: string?
    The optional localization key, or `null` if not set.
    TraceId: string?
    The optional OpenTelemetry trace identifier, or `null` if not set.

    Registered in `AspNetCoreJsonSerializerContext` for AOT-safe serialization. It is used internally to populate the `errors` array in RFC 9457 ProblemDetails extensions. Properties: - `Code` — application error code (e.g., `"ORDER.EXPIRED"`). - `Description` — human-readable error message. - `Type` — `ErrorType` as a PascalCase string (e.g., `"Validation"`). - `Severity` — `ErrorSeverity` as a PascalCase string (e.g., `"Error"`). - `Retryability` — `ErrorRetryability` as a PascalCase string (e.g., `"Transient"`). - `DescriptionKey` — optional localization key, or `null` if not set. - `TraceId` — optional OpenTelemetry trace ID, or `null` if not set.

  • propertyCode
    public string Code { get; init; }

    The application-specific error code.

  • propertyDescription
    public string Description { get; init; }

    The human-readable description of the error.

  • propertyDescriptionKey
    public string? DescriptionKey { get; init; }

    The optional localization key, or `null` if not set.

  • propertyRetryability
    public string Retryability { get; init; }

    The string representation of the `ErrorRetryability`.

  • propertySeverity
    public string Severity { get; init; }

    The string representation of the `ErrorSeverity`.

  • propertyTraceId
    public string? TraceId { get; init; }

    The optional OpenTelemetry trace identifier, or `null` if not set.

  • propertyType
    public string Type { get; init; }

    The string representation of the `ErrorType`.

class

ProblemDetailsExceptionHandler

Assembly: EricksonLopez.Result.AspNetCore
public sealed partial class ProblemDetailsExceptionHandler : IExceptionHandler
Implements: IExceptionHandler

Hardened, NativeAOT-compatible RFC 9457 `IExceptionHandler` combining resilience status mapping (`503 Service Unavailable` + `Retry-After` on circuit breaker / timeout trips, `413`/`400` on Kestrel bad requests, `499` on client-aborted requests) with strict `IsDevelopment()` error message redaction and `Response.HasStarted` safety.

Members (2)

  • constructorProblemDetailsExceptionHandler
    public ProblemDetailsExceptionHandler(IHostEnvironment environment, ILogger<ProblemDetailsExceptionHandler> logger)

    Initializes a new instance of the `ProblemDetailsExceptionHandler` class.

    environment: IHostEnvironment
    The hosting environment used to gate exception detail exposure strictly to Development.
    logger: ILogger<ProblemDetailsExceptionHandler>
    The structured logger.
  • methodTryHandleAsync
    public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    httpContext: HttpContext
    exception: Exception
    cancellationToken: CancellationToken
class

ResultEndpointFilter

Assembly: EricksonLopez.Result.AspNetCore
public sealed class ResultEndpointFilter : IEndpointFilter
Implements: IEndpointFilter

Provides a minimal API endpoint filter that automatically transforms returned `Result` and `Result<T>` instances into HTTP responses. Completely reflection-free and NativeAOT compatible.

Remarks:

⚠ OpenAPI / Swagger metadata: When using this filter with `Result<T>`, the success value is returned as `object?` via `IResultOutcome.RawValue`. This means OpenAPI/Swagger will show `object` instead of the concrete type `T`. To fix this, explicitly declare the response type on your endpoint:

app.MapGet("/orders/{id}", Handler)
   .AddResultEndpointFilter()
   .Produces<OrderDto>(StatusCodes.Status200OK)
   .ProducesProblem(StatusCodes.Status404NotFound);

Alternatively, call `ResultHttpExtensions.ToHttpResult<T>` directly from your handler to get typed `Ok<T>` results with proper OpenAPI metadata without needing `.Produces<T>()`.

Members (3)

  • constructorResultEndpointFilter
    public ResultEndpointFilter(IOptions<ResultHttpOptions>? options = null)

    Initializes a new instance of the `ResultEndpointFilter` class using DI options.

    options: IOptions<ResultHttpOptions>?
    The configured HTTP options from dependency injection, or `null` to use defaults.
  • constructorResultEndpointFilter
    public ResultEndpointFilter(ResultHttpOptions? options)

    Initializes a new instance of the `ResultEndpointFilter` class.

    options: ResultHttpOptions?
    Optional HTTP mapping options.
  • methodInvokeAsync
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)

    Inherits documentation from base type or interface.

    context: EndpointFilterInvocationContext
    next: EndpointFilterDelegate
class

ResultEndpointRouteBuilderExtensions

Assembly: EricksonLopez.Result.AspNetCore
public static class ResultEndpointRouteBuilderExtensions

Provides extension methods for configuring Result endpoints on route builders.

Members (3)

  • methodAddResultEndpointFilter
    public static RouteGroupBuilder AddResultEndpointFilter(this RouteGroupBuilder builder)

    Adds the `ResultEndpointFilter` to the route group. This filter automatically converts returned `Result` and `Result<T>` instances into appropriate HTTP responses, including RFC 9457 Problem Details for failures.

    builder: this RouteGroupBuilder
    The route group builder.

    Returns: A `RouteGroupBuilder` that can be used to further customize the endpoint.

    When added at the route group level, all endpoints in the group have their `Result` and `Result<T>` return values automatically unwrapped. See the `AddResultEndpointFilter(RouteHandlerBuilder)` overload for important notes on OpenAPI schema requirements and boxing tradeoffs.

  • methodAddResultEndpointFilter
    public static RouteHandlerBuilder AddResultEndpointFilter(this RouteHandlerBuilder builder)

    Adds the `ResultEndpointFilter` to the route handler. This filter automatically converts returned `Result` and `Result<T>` instances into appropriate HTTP responses, including RFC 9457 Problem Details for failures.

    builder: this RouteHandlerBuilder
    The route handler builder to add the filter to.

    Returns: The `builder` for chaining.

    OpenAPI / Swagger schema: The filter returns `Ok<object?>` internally because it accesses the success value via the `IResultOutcome.RawValue` covariant property. OpenAPI tooling (Swashbuckle, NSwag, Scalar) cannot infer the concrete response schema automatically. You must add `.Produces<T>(StatusCodes.Status200OK)` to your endpoint to get an accurate Swagger schema. The Roslyn analyzer `RESULT008` (`EndpointFilterOpenApiAnalyzer`) warns at compile time if `.Produces<T>()` is missing. Boxing tradeoff: `Result<T>` is a struct. The filter detects it via `result is IResultOutcome`, which boxes the struct on every request (1 heap allocation). If `T` is also a value type, the success value is additionally boxed via `RawValue` (2 allocations total per request). This is acceptable for most endpoints. For high-throughput paths (> 10k req/s) where zero allocation on the success path is required, call `result.ToHttpResult()` directly from the handler:

    app.MapGet("/orders/{id}", async (Guid id, IOrderService svc) =>
    {
        var result = await svc.GetOrderAsync(id);
        return result.ToHttpResult(); // typed Ok<OrderDto>, zero boxing, full OpenAPI
    });

    Uninitialized result protection: If the handler returns a `default(Result<T>)` (an uninitialized struct), the filter detects this via `IResultOutcome.IsUninitialized` and throws `InvalidOperationException` rather than producing a silent `200 OK` response with a `null` body.

  • methodProducesResult<T>
    public static RouteHandlerBuilder ProducesResult<T>(this IEndpointConventionBuilder builder, int statusCode = StatusCodes.Status200OK)

    Configures the endpoint to produce a strongly typed `T` on success (default 200 OK) and a `Mvc.ProblemDetails` on failure (400 Bad Request).

    builder: this IEndpointConventionBuilder
    The endpoint convention builder (such as `RouteHandlerBuilder`).
    statusCode: int
    The HTTP status code for success (defaults to 200 OK).

    Returns: The `builder` as a `RouteHandlerBuilder` when applicable.

    Serves as an ergonomic wrapper around `.Produces<T>()` and `.Produces<ProblemDetails>()` to fix the OpenAPI degradation (schema `object`) introduced by `AddResultEndpointFilter(RouteHandlerBuilder)`. When both `EricksonLopez.Result.AspNetCore` and `EricksonLopez.Result.OpenApi` are imported, the more specific `RouteHandlerBuilder` overload in `EricksonLopez.Result.OpenApi` takes precedence without `CS0121` ambiguity. Type parameters: T: The success response type.

class

ResultHttpExtensions

Assembly: EricksonLopez.Result.AspNetCore
public static class ResultHttpExtensions

Provides HTTP integration extensions for Result types.

Members (4)

  • methodToHttpResult
    public static Microsoft.AspNetCore.Http.IResult ToHttpResult(this in Result result, ResultHttpOptions? options = null)

    Converts a successful `Result` to a status response, and a failed `Result` to a ProblemDetails response.

    result: this in Result
    The result to convert, passed by readonly reference.
    options: ResultHttpOptions?
    Optional HTTP options to customize status codes and problem details mapping, or `null` to use default options.

    Returns: An `Http.IResult` representing either the success status response or the failure ProblemDetails response.

    The following success status codes map to `TypedResults.*` methods for full OpenAPI inference: 200 OK, 201 Created, 202 Accepted, 204 No Content. All other codes use `TypedResults.StatusCode` which is opaque to OpenAPI tooling. If you configure a non-standard success code and need OpenAPI to infer it, use `ToHttpResult<T>(in Result<T>, ResultHttpOptions?)` or return the `Http.TypedResults` value directly from your endpoint handler. ⚠️ RFC 9110 §15.3.2 note: When `ResultHttpOptions.DefaultSuccessStatusCode` is `StatusCodes.Status201Created`, the generated response does NOT include a `Location` header. RFC 9110 §15.3.2 states that a 201 response SHOULD include a `Location` header with the URI of the newly created resource. If a `Location` header is required, return `TypedResults.Created(uri, value)` directly from your endpoint handler instead of calling this extension.

  • methodToHttpResult<T>
    public static Microsoft.AspNetCore.Http.IResult ToHttpResult<T>(this in Result<T> result, ResultHttpOptions? options = null)

    Converts a successful `Result<T>` to a 200 OK response with the value, and a failed `Result<T>` to a ProblemDetails response.

    result: this in Result<T>
    The result to convert, passed by readonly reference.
    options: ResultHttpOptions?
    Optional HTTP options to customize status codes and problem details mapping, or `null` to use default options.

    Returns: An `Http.IResult` representing either the 200 OK response or the failure ProblemDetails response.

    Type parameters: T: The value type of the result.

  • methodToProblemDetails
    public static Microsoft.AspNetCore.Http.IResult ToProblemDetails(this in Result result, ResultHttpOptions? options = null)

    Converts a failed `Result` into an ASP.NET Core `Http.IResult` containing an RFC 9457 ProblemDetails response.

    result: this in Result
    The failed result to convert, passed by readonly reference.
    options: ResultHttpOptions?
    Optional HTTP options to customize status codes and problem details mapping, or `null` to use default options.

    Returns: An `Http.IResult` representing the ProblemDetails response.

    Exceptions: InvalidOperationException: `result` is a successful result

  • methodToProblemDetails<T>
    public static Microsoft.AspNetCore.Http.IResult ToProblemDetails<T>(this in Result<T> result, ResultHttpOptions? options = null)

    Converts a failed `Result<T>` into an ASP.NET Core `Http.IResult` containing an RFC 9457 ProblemDetails response.

    result: this in Result<T>
    The failed result to convert, passed by readonly reference.
    options: ResultHttpOptions?
    Optional HTTP options to customize status codes and problem details mapping, or `null` to use default options.

    Returns: An `Http.IResult` representing the ProblemDetails response.

    Type parameters: T: The value type of the result. Exceptions: InvalidOperationException: `result` is a successful result

class

ResultHttpOptions

Assembly: EricksonLopez.Result.AspNetCore
public sealed class ResultHttpOptions

Represents configurable options for HTTP mapping of Result error types to HTTP Status Codes and ProblemDetails parameters.

Remarks:

Configuration: Use `ConfigureStatusCode` and the scalar properties (`DefaultSuccessStatusCode`, `IncludeDescription`, `IncludeTraceId`, `DefaultFallbackDescription`, `TypeUriBase`) to configure behavior. All configuration must be done before the first request is processed. Any mutation attempt after the first request throws an `InvalidOperationException`. Thread safety: Configure all options during application startup before any requests are handled. After the first call to `GetFrozenStatusCodeMap`, the options are fully frozen and ALL mutation attempts (dictionaries and scalar properties alike) throw `InvalidOperationException`. NativeAOT / Trimming warning: When using `ResultEndpointFilter` with `Result<T>`, the success value is returned as `object?` via `IResultOutcome.RawValue`. ASP.NET Core will serialize this using the configured `Json.JsonSerializerOptions`. For NativeAOT compatibility, ensure the concrete type `T` is registered in your `Serialization.JsonSerializerContext`. ⚠️ Performance trade-off (boxing): `Result<T>` is a `readonly struct`. When the endpoint filter checks `result is IResultOutcome`, the struct is boxed to the managed heap for the duration of the polymorphic dispatch. This is a single allocation per request on the failure path and is negligible in typical web workloads. If extreme hot-path allocation avoidance is required, call `ResultHttpExtensions.ToHttpResult<T>` directly from your handler instead of using the filter.

Members (10)

  • methodConfigureStatusCode
    public ResultHttpOptions ConfigureStatusCode(ErrorType type, int statusCode)

    Overrides the HTTP status code for a specific `ErrorType`.

    type: ErrorType
    The error type to configure.
    statusCode: int
    The HTTP status code to map to.

    Returns: This instance for method chaining.

    Thread safety: Acquires the internal freeze lock to be mutually exclusive with `GetFrozenStatusCodeMap`. This prevents a TOCTOU race where a frozen snapshot could be captured between the guard check and the dictionary write. Configure all options before the first request; concurrent configuration is not supported. Exceptions: InvalidOperationException: The method is called after the first request has been processed (options are frozen)

  • methodConfigureTitleOverride
    public ResultHttpOptions ConfigureTitleOverride(ErrorType type, string title)

    Configures a title override for the specified `ErrorType`.

    type: ErrorType
    The error type to override the title for.
    title: string
    The custom title to use in ProblemDetails.

    Returns: This instance for fluent chaining.

    options.ConfigureTitleOverride(ErrorType.Custom, "Payment Error")
           .ConfigureTitleOverride(ErrorType.Domain, "Business Rule Violation");

    Exceptions: InvalidOperationException: The method is called after the first request has been processed (options are frozen)

  • methodIncludeDescriptionInDevelopment
    public ResultHttpOptions IncludeDescriptionInDevelopment(Microsoft.Extensions.Hosting.IHostEnvironment environment)

    Enables `IncludeDescription` when the application is running in the development environment, and leaves it disabled in all other environments.

    environment: Microsoft.Extensions.Hosting.IHostEnvironment
    The current `Hosting.IHostEnvironment`.

    Returns: This `ResultHttpOptions` instance for fluent chaining.

    This is a convenience method to apply the recommended pattern for description exposure: show descriptions in development for faster debugging, hide them in staging/production to avoid information leakage.

    services.Configure<ResultHttpOptions>(options =>
        options.IncludeDescriptionInDevelopment(env));

    Exceptions: ArgumentNullException: `environment` is `null`; InvalidOperationException: The method is called after the first request has been processed (options are frozen)

  • propertyDefaultFallbackDescription
    public string DefaultFallbackDescription { get; set; }

    Gets or sets the generic description used in ProblemDetails when `IncludeDescription` is `false` (the secure default). Defaults to `"An error occurred."`.

    Override this to customise the fallback message for branding, internationalisation, or security policy requirements. For example:

    services.Configure<ResultHttpOptions>(options =>
        options.DefaultFallbackDescription = "An unexpected error occurred. Please contact support.");

    Exceptions: InvalidOperationException: The property is set after the first request has been processed (options are frozen)

  • propertyDefaultSuccessStatusCode
    public int DefaultSuccessStatusCode { get; set; }

    Gets or sets the default HTTP status code returned for successful non-generic Result instances. Defaults to `StatusCodes.Status204NoContent` for command-style operations.

    Exceptions: InvalidOperationException: The property is set after the first request has been processed (options are frozen)

  • propertyIncludeDescription
    public bool IncludeDescription { get; set; }

    Gets or sets a value indicating whether to include the full `description` in ProblemDetails error extensions. Defaults to `false` for secure-by-default behavior.

    ⚠ Security warning: Error descriptions may contain sensitive infrastructure details (connection strings, internal paths, service names, stack trace fragments). This option defaults to `false` to prevent information leakage in production environments. When `false`, the description field in `ErrorDetailDto` is replaced with a generic message (`"An error occurred."`). The full description remains available via `Error.Description` for internal logging and observability. Enabling for development only (recommended pattern):

    // Option 1 — fluent convenience method:
    services.Configure<ResultHttpOptions>(options =>
        options.IncludeDescriptionInDevelopment(env));
    
    // Option 2 — manual conditional:
    services.Configure<ResultHttpOptions>(options =>
        options.IncludeDescription = env.IsDevelopment());

    Exceptions: InvalidOperationException: The property is set after the first request has been processed (options are frozen)

  • propertyIncludeTraceId
    public bool IncludeTraceId { get; set; }

    Gets or sets a value indicating whether to include `traceId` in ProblemDetails error extensions. Defaults to `false` to avoid exposing distributed trace identifiers to external clients, which can aid in correlating attacks or revealing infrastructure details. Set to `true` when building internal APIs where trace correlation is valuable.

    When `false`, the `traceId` field is omitted from `ErrorDetailDto` in the ProblemDetails extensions. The trace ID is still captured and available via `Error.TraceId` for internal logging and observability. Exceptions: InvalidOperationException: The property is set after the first request has been processed (options are frozen)

  • propertyStatusCodeMap
    public IReadOnlyDictionary<ErrorType, int> StatusCodeMap { get; }

    Gets a read-only view of the current status code map. To modify mappings, use `ConfigureStatusCode` before the first request.

    Returns a cached `ReadOnlyDictionary<TKey, TValue>` wrapper to prevent consumers from casting back to the underlying `Dictionary<TKey, TValue>` and bypassing the `ConfigureStatusCode` freeze guard. The wrapper is cached to avoid heap allocation on every access. The cache is invalidated when `ConfigureStatusCode` is called.

  • propertyTitleOverrides
    public IReadOnlyDictionary<ErrorType, string> TitleOverrides { get; }

    Gets the dictionary of custom ProblemDetails `title` values for specific `ErrorType` values. When an entry is present for an `ErrorType`, it overrides the default title.

    Use `ConfigureTitleOverride` to set domain-specific titles for error types. This property exposes the overrides as a read-only view for inspection. Mutations are protected by the same freeze guard as `ConfigureStatusCode`. Thread safety and cast protection: This property returns a cached `ReadOnlyDictionary<TKey, TValue>` wrapper that prevents consumers from casting back to the underlying `Dictionary<TKey, TValue>` and bypassing the freeze guard. All mutations must go through `ConfigureTitleOverride` during application startup.

  • propertyTypeUriBase
    public string TypeUriBase { get; set; }

    Gets or sets the default base URI format for RFC 9457 problem details types.

    RFC 9457 §4.2.1 recommends `"about:blank"` as the `type` URI when there is no specific URI describing the problem type. When this property is set to the default `"about:blank"`, the `type` field in ProblemDetails will be exactly `"about:blank"` (no section suffix appended), conforming to the RFC. To include RFC 9110 section links in `type`, set: `options.TypeUriBase = "https://www.rfc-editor.org/rfc/rfc9110#section-";` This will produce URIs like `"https://www.rfc-editor.org/rfc/rfc9110#section-15.5.1"`. To use application-specific problem type URIs, set the base URL of your own error catalog: `options.TypeUriBase = "https://api.myapp.com/errors/";` Note: When this value is exactly `"about:blank"`, the HTTP status section suffix is NOT appended to avoid producing the invalid URI `"about:blank#15.5.1"`. For any other base URI, the RFC 9110 status section suffix is appended normally. Exceptions: InvalidOperationException: The property is set after the first request has been processed (options are frozen)

class

ResultMvcExtensions

Assembly: EricksonLopez.Result.AspNetCore
public static class ResultMvcExtensions

Provides ASP.NET Core MVC `IActionResult` extensions for `Result` and `Result<T>`.

Members (2)

  • methodToActionResult
    public static IActionResult ToActionResult(this in Result result, ResultHttpOptions? options = null)

    Converts a non-generic `Result` into an `IActionResult`. Returns `NoContentResult` on success or an `ObjectResult` containing RFC 9457 `ProblemDetails` on failure.

    result: this in Result
    The result instance passed by readonly reference.
    options: ResultHttpOptions?
    Optional HTTP mapping options.

    Returns: An `IActionResult` representing the HTTP response.

  • methodToActionResult<T>
    public static IActionResult ToActionResult<T>(this in Result<T> result, ResultHttpOptions? options = null)

    Converts a `Result<T>` into an `IActionResult`. Returns `OkObjectResult` on success or an `ObjectResult` containing RFC 9457 `ProblemDetails` on failure.

    result: this in Result<T>
    The result instance passed by readonly reference.
    options: ResultHttpOptions?
    Optional HTTP mapping options.

    Returns: An `IActionResult` representing the HTTP response.

    Type parameters: T: The result value type.

class

ResultServiceCollectionExtensions

Assembly: EricksonLopez.Result.AspNetCore
public static class ResultServiceCollectionExtensions

Provides extension methods for registering Result HTTP integration services in an `IServiceCollection`.

Members (3)

  • methodAddResultExceptionHandler
    public static IServiceCollection AddResultExceptionHandler(this IServiceCollection services, Action<ResultHttpOptions>? configure = null)

    Registers `ProblemDetailsExceptionHandler` alongside RFC 9457 ProblemDetails and NativeAOT JSON serialization.

    services: this IServiceCollection
    The service collection to add services to.
    configure: Action<ResultHttpOptions>?
    An optional delegate to configure `ResultHttpOptions`.

    Returns: The original `IServiceCollection` for chaining.

  • methodAddResultHttpOptions
    public static IServiceCollection AddResultHttpOptions(this IServiceCollection services, Action<ResultHttpOptions>? configure = null)

    Registers `ResultHttpOptions` with the ASP.NET Core options system, optionally configuring the options using the provided `configure` delegate.

    services: this IServiceCollection
    The service collection to add services to.
    configure: Action<ResultHttpOptions>?
    An optional delegate to configure `ResultHttpOptions` during application startup. All calls to `ResultHttpOptions.ConfigureStatusCode` must be made before the first request is processed. After the first request, the options are frozen.

    Returns: The original `IServiceCollection` for chaining.

    Example:

    builder.Services.AddResultHttpOptions(options =>
    {
        options.ConfigureStatusCode(ErrorType.Failure, StatusCodes.Status422UnprocessableEntity);
        options.DefaultSuccessStatusCode = StatusCodes.Status200OK;
    });
    
    // Then add the filter to your endpoint or group:
    app.MapPost("/cmd", Handler).AddResultEndpointFilter();
  • methodAddResultProblemDetails
    public static IServiceCollection AddResultProblemDetails(this IServiceCollection services, Action<ResultHttpOptions>? configure = null)

    Registers ASP.NET Core ProblemDetails services along with `ResultHttpOptions` and `AspNetCoreJsonSerializerContext` for NativeAOT-compatible RFC 9457 ProblemDetails serialization.

    services: this IServiceCollection
    The service collection to add services to.
    configure: Action<ResultHttpOptions>?
    An optional delegate to configure `ResultHttpOptions`.

    Returns: The original `IServiceCollection` for chaining.

EricksonLopez.Result.Dapr#

4
class

DaprErrorCodes

Assembly: EricksonLopez.Result.Dapr
public static class DaprErrorCodes

Provides standardized domain error codes for Dapr operations.

Members (4)

  • fieldEtagMismatch
    public const string EtagMismatch

    Error code emitted when saving or deleting state fails due to an ETag concurrency mismatch.

  • fieldOperationFailed
    public const string OperationFailed

    Error code emitted when a generic Dapr operation fails.

  • fieldSidecarUnavailable
    public const string SidecarUnavailable

    Error code emitted when communication with the Dapr sidecar fails or is unavailable.

  • fieldStateNotFound
    public const string StateNotFound

    Error code emitted when a requested state entry does not exist in the state store.

record

DaprErrorResponse

Assembly: EricksonLopez.Result.Dapr
public sealed record DaprErrorResponse(string Status, string Code, string Description)

Represents the payload returned to Dapr Pub/Sub endpoints when a message is dropped.

Members (4)

  • constructorDaprErrorResponse
    public DaprErrorResponse(string Status, string Code, string Description)

    Initializes a new instance of DaprErrorResponse.

    Status: string
    The disposition status for Dapr ("DROP").
    Code: string
    The domain error code.
    Description: string
    The error description.
  • propertyCode
    public string Code { get; init; }

    The domain error code.

  • propertyDescription
    public string Description { get; init; }

    The error description.

  • propertyStatus
    public string Status { get; init; }

    The disposition status for Dapr ("DROP").

class

DaprResultPubSubExtensions

Assembly: EricksonLopez.Result.Dapr
public static class DaprResultPubSubExtensions

Provides extension methods for mapping `Result` and `Result<TValue>` outcomes to Dapr Pub/Sub HTTP endpoint results based on `ErrorRetryability`.

Members (2)

  • methodToDaprTopicResult
    public static IResult ToDaprTopicResult(this Result result)

    Translates a `Result` outcome into an HTTP `IResult` configured for Dapr Pub/Sub topic endpoints.

    result: this Result
    The outcome to translate.

    Returns: Returns HTTP 200 OK on success (ACK), HTTP 503 Service Unavailable for transient errors (triggers Dapr RETRY), or HTTP 422 Unprocessable Entity for permanent errors (triggers Dapr DROP / Dead-letter).

  • methodToDaprTopicResult<T>
    public static IResult ToDaprTopicResult<T>(this Result<T> result)

    Translates a `Result<TValue>` outcome into an HTTP `IResult` configured for Dapr Pub/Sub topic endpoints.

    result: this Result<T>
    The outcome to translate.

    Returns: Returns HTTP 200 OK on success with value (ACK), HTTP 503 Service Unavailable for transient errors (triggers Dapr RETRY), or HTTP 422 Unprocessable Entity for permanent errors (triggers Dapr DROP / Dead-letter).

    Type parameters: T: The result value type.

class

DaprResultStateExtensions

Assembly: EricksonLopez.Result.Dapr
public static class DaprResultStateExtensions

Provides extension methods on `DaprClient` for converting state store operations into strongly-typed `Result` and `Result<TValue>` instances.

Members (3)

  • methodDeleteStateWithResultAsync
    public static async Task<Result> DeleteStateWithResultAsync(this DaprClient daprClient, string storeName, string key, string etag, StateOptions? stateOptions = null, IReadOnlyDictionary<string, string>? metadata = null, CancellationToken cancellationToken = default)

    Asynchronously deletes state from a Dapr state store with optimistic concurrency checking via ETag.

    daprClient: this DaprClient
    The Dapr client instance.
    storeName: string
    The name of the state store component.
    key: string
    The key of the state to delete.
    etag: string
    The expected ETag for optimistic concurrency verification.
    stateOptions: StateOptions?
    Optional state options controlling concurrency and consistency.
    metadata: IReadOnlyDictionary<string, string>?
    Optional metadata for the state store operation.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Returns: A result indicating success or a concurrency conflict error on failure.

  • methodGetStateWithResultAsync<T>
    public static async Task<Result<T>> GetStateWithResultAsync<T>(this DaprClient daprClient, string storeName, string key, ConsistencyMode? consistencyMode = null, IReadOnlyDictionary<string, string>? metadata = null, CancellationToken cancellationToken = default)

    Asynchronously retrieves state from a Dapr state store, mapping missing keys to `Error.NotFound`.

    daprClient: this DaprClient
    The Dapr client instance.
    storeName: string
    The name of the state store component.
    key: string
    The key of the state to retrieve.
    consistencyMode: ConsistencyMode?
    The optional consistency mode.
    metadata: IReadOnlyDictionary<string, string>?
    Optional metadata for the state store operation.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Returns: A result containing the state value on success, or a mapped domain error on failure.

    Type parameters: T: The type of state value.

  • methodSaveStateWithResultAsync<T>
    public static async Task<Result<T>> SaveStateWithResultAsync<T>(this DaprClient daprClient, string storeName, string key, T value, string etag, StateOptions? stateOptions = null, IReadOnlyDictionary<string, string>? metadata = null, CancellationToken cancellationToken = default)

    Asynchronously saves state to a Dapr state store with optimistic concurrency checking via ETag.

    daprClient: this DaprClient
    The Dapr client instance.
    storeName: string
    The name of the state store component.
    key: string
    The key of the state to save.
    value: T
    The value of the state to save.
    etag: string
    The expected ETag for optimistic concurrency verification.
    stateOptions: StateOptions?
    Optional state options controlling concurrency and consistency.
    metadata: IReadOnlyDictionary<string, string>?
    Optional metadata for the state store operation.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Returns: A result containing the saved value on success, or a concurrency conflict error on failure.

    Type parameters: T: The type of state value.

EricksonLopez.Result.DomainErrors.Generators#

4
class

DomainErrorClassModel

Assembly: EricksonLopez.Result.DomainErrors.Generators
public sealed class DomainErrorClassModel : IEquatable<DomainErrorClassModel>
Implements: IEquatable<DomainErrorClassModel>

Represents the parsed declaration of a domain error class containing one or more domain errors.

Members (7)

  • constructorDomainErrorClassModel
    public DomainErrorClassModel(string namespaceName, string className, ImmutableArray<DomainErrorModel> errors)

    Initializes a new instance of the `DomainErrorClassModel` class.

    namespaceName: string
    The containing C# namespace.
    className: string
    The static class name to generate.
    errors: ImmutableArray<DomainErrorModel>
    The collection of domain errors.
  • methodEquals
    public bool Equals(DomainErrorClassModel? other)

    Inherits documentation from base type or interface.

    other: DomainErrorClassModel?
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • propertyClassName
    public string ClassName { get; }

    Gets the class name.

  • propertyErrors
    public ImmutableArray<DomainErrorModel> Errors { get; }

    Gets the domain error declarations.

  • propertyNamespaceName
    public string NamespaceName { get; }

    Gets the namespace name.

class

DomainErrorModel

Assembly: EricksonLopez.Result.DomainErrors.Generators
public sealed class DomainErrorModel : IEquatable<DomainErrorModel>
Implements: IEquatable<DomainErrorModel>

Represents the declaration of a single domain error item within a domain error schema file.

Members (12)

  • constructorDomainErrorModel
    public DomainErrorModel(string name, string code, string description, string? type, string? severity, string? retryability, string? descriptionKey, ImmutableArray<DomainErrorParameterModel> parameters)

    Initializes a new instance of the `DomainErrorModel` class.

    name: string
    The method name of the error factory.
    code: string
    The unique error code identifier.
    description: string
    The default human-readable error description template.
    type: string?
    The domain error type classification.
    severity: string?
    The optional error severity level.
    retryability: string?
    The optional error retryability classification.
    descriptionKey: string?
    The optional localization key.
    parameters: ImmutableArray<DomainErrorParameterModel>
    The parameter list for parameterization.
  • methodEquals
    public bool Equals(DomainErrorModel? other)

    Inherits documentation from base type or interface.

    other: DomainErrorModel?
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • propertyCode
    public string Code { get; }

    Gets the unique error code.

  • propertyDescription
    public string Description { get; }

    Gets the description format string.

  • propertyDescriptionKey
    public string? DescriptionKey { get; }

    Gets the localization key, if specified.

  • propertyName
    public string Name { get; }

    Gets the factory method name.

  • propertyParameters
    public ImmutableArray<DomainErrorParameterModel> Parameters { get; }

    Gets the method parameters.

  • propertyRetryability
    public string? Retryability { get; }

    Gets the retryability classification, if specified.

  • propertySeverity
    public string? Severity { get; }

    Gets the error severity level, if specified.

  • propertyType
    public string Type { get; }

    Gets the error type (e.g. Failure, NotFound, Validation, Conflict, Unauthorized, Forbidden, Unavailable, Unexpected).

class

DomainErrorParameterModel

Assembly: EricksonLopez.Result.DomainErrors.Generators
public sealed class DomainErrorParameterModel : IEquatable<DomainErrorParameterModel>
Implements: IEquatable<DomainErrorParameterModel>

Represents a strongly-typed parameter declaration for a generated domain error factory method.

Members (6)

  • constructorDomainErrorParameterModel
    public DomainErrorParameterModel(string name, string type)

    Initializes a new instance of the `DomainErrorParameterModel` class.

    name: string
    The name of the parameter.
    type: string
    The type of the parameter (e.g. `string`, `System.Guid`).
  • methodEquals
    public bool Equals(DomainErrorParameterModel? other)

    Inherits documentation from base type or interface.

    other: DomainErrorParameterModel?
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • propertyName
    public string Name { get; }

    Gets the parameter name.

  • propertyType
    public string Type { get; }

    Gets the parameter type name.

class

DomainErrorsGenerator

Assembly: EricksonLopez.Result.DomainErrors.Generators
public sealed class DomainErrorsGenerator : IIncrementalGenerator
Implements: IIncrementalGenerator

Represents an incremental source generator producing strongly-typed domain error factory classes from `*.errors.json` and `*.domainerrors.json` additional file declarations.

Members (1)

  • methodInitialize
    public void Initialize(IncrementalGeneratorInitializationContext context)

    Inherits documentation from base type or interface.

    context: IncrementalGeneratorInitializationContext

EricksonLopez.Result.EntityFrameworkCore#

2
class

EntityFrameworkErrorCodes

Assembly: EricksonLopez.Result.EntityFrameworkCore
public static class EntityFrameworkErrorCodes

Defines canonical, well-known domain error codes for Entity Framework Core persistence operations.

Members (6)

  • fieldConcurrencyConflict
    public const string ConcurrencyConflict

    Error code emitted when an optimistic concurrency conflict occurs during database updates.

  • fieldEntityNotFound
    public const string EntityNotFound

    Error code emitted when an expected entity does not exist in the database.

  • fieldMultipleEntitiesFound
    public const string MultipleEntitiesFound

    Error code emitted when a single entity was expected but multiple matching records were found.

  • fieldTimeout
    public const string Timeout

    Error code emitted when a database operation times out.

  • fieldUnexpected
    public const string Unexpected

    Error code emitted when an unexpected database exception occurs.

  • fieldUpdateFailed
    public const string UpdateFailed

    Error code emitted when a generic database update constraint or execution failure occurs.

class

EntityFrameworkResultExtensions

Assembly: EricksonLopez.Result.EntityFrameworkCore
public static class EntityFrameworkResultExtensions

Provides extension methods for Entity Framework Core `DbContext` and `IQueryable<T>` enabling direct, exception-safe conversion of database operations into `Result<TValue>`.

Members (4)

  • methodFirstOrDefaultToResultAsync<T>
    public static async Task<Result<T>> FirstOrDefaultToResultAsync<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate, Error notFoundError, CancellationToken cancellationToken = default) where T : class

    Asynchronously returns the first element of a sequence that satisfies a specified condition, or a domain `Result<TValue>` failure with the specified `notFoundError` if no such element is found.

    source: this IQueryable<T>
    An `IQueryable<T>` to return an element from.
    predicate: Expression<Func<T, bool>>
    A function to test each element for a condition.
    notFoundError: Error
    The error to return if no matching element is found.
    cancellationToken: CancellationToken
    A `CancellationToken` to observe while waiting for the task to complete.

    Returns: A task that represents the asynchronous operation containing the matching entity or a failure.

    Type parameters: T: The type of the elements of `source`.

  • methodSaveChangesAsyncToResult
    public static async Task<Result<int>> SaveChangesAsyncToResult(this DbContext context, CancellationToken cancellationToken = default)

    Asynchronously saves all changes made in this context to the database, mapping common persistence exceptions to strongly-typed domain `Result<TValue>` failures.

    context: this DbContext
    The database context instance.
    cancellationToken: CancellationToken
    A `CancellationToken` to observe while waiting for the task to complete.

    Returns: A task representing the asynchronous save operation. The result contains the number of state entries written to the database on success, or a mapped domain `Error` on failure.

  • methodSingleOrDefaultToResultAsync<T>
    public static async Task<Result<T>> SingleOrDefaultToResultAsync<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate, Error notFoundError, CancellationToken cancellationToken = default) where T : class

    Asynchronously returns the single, specific element of a sequence that satisfies a specified condition, or a domain `Result<TValue>` failure if no such element or multiple elements are found.

    source: this IQueryable<T>
    An `IQueryable<T>` to return a single element from.
    predicate: Expression<Func<T, bool>>
    A function to test each element for a condition.
    notFoundError: Error
    The error to return if no matching element is found.
    cancellationToken: CancellationToken
    A `CancellationToken` to observe while waiting for the task to complete.

    Returns: A task containing the matching entity or a failure.

    Type parameters: T: The type of the elements of `source`.

  • methodToListToResultAsync<T>
    public static async Task<Result<List<T>>> ToListToResultAsync<T>(this IQueryable<T> source, CancellationToken cancellationToken = default)

    Asynchronously creates a `List<T>` from an `IQueryable<T>` wrapped in a `Result<TValue>`.

    source: this IQueryable<T>
    An `IQueryable<T>` to create a list from.
    cancellationToken: CancellationToken
    A `CancellationToken` to observe while waiting for the task to complete.

    Returns: A task containing the materialized list or an unexpected error on failure.

    Type parameters: T: The type of the elements of `source`.

EricksonLopez.Result.FluentValidation#

2
class

FluentValidationResultExtensions

Assembly: EricksonLopez.Result.FluentValidation
public static class FluentValidationResultExtensions

Provides extension methods for converting FluentValidation `ValidationResult` to `Result` and `Result<T>`.

Remarks:

Converts validation failures into structured `Error` instances with: - `ErrorType.Validation` type - Error code from `ValidationFailure.ErrorCode` (or property name fallback) - Description from `ValidationFailure.ErrorMessage` - Inner errors for each individual validation failure - Metadata with property name, attempted value, and severity ? ErrorCode behavior: FluentValidation sets `ValidationFailure.ErrorCode` to the validator type name by default (e.g., `"NotEmptyValidator"`, `"GreaterThanValidator"`). This does NOT follow the `"Domain.Property"` naming convention used by the rest of this library. When using default FluentValidation validators, the generated error codes will be validator type names, not domain codes. To produce domain-consistent error codes (e.g., `"Order.Customer.Required"`), use FluentValidation's `.WithErrorCode()` extension on each rule:

RuleFor(x => x.Customer)
    .NotEmpty()
    .WithErrorCode("Order.Customer.Required");

Without `.WithErrorCode()`, the fallback is `"Validation.{PropertyName}"` (e.g., `"Validation.Customer"`), which is better than a validator type name but still not a fully qualified domain code. Note: `ValidationFailure.CustomState` is not propagated to error metadata. Use `ValidationFailure.CustomState` if you need structured data from validators and access it before conversion, or set metadata via `.WithState()` with a `Dictionary<TKey, TValue>` and convert via a custom overload.

Members (8)

  • methodEnsureValid<T>
    public static Result<T> EnsureValid<T>(this in Result<T> result, global::FluentValidation.IValidator<T> validator)

    Integrates validation into a Result pipeline. Validates the value of a successful `Result<T>` and returns a validation failure if invalid.

    result: this in Result<T>
    The result containing the value to validate, passed by readonly reference.
    validator: global::FluentValidation.IValidator<T>
    The FluentValidation validator.

    Returns: The original result if valid, or a validation failure result.

    Type parameters: T: The type of the value to validate. Exceptions: InvalidOperationException: `result` is an uninitialized default value Example:

    var result = await GetOrderAsync()
        .EnsureValid(new OrderValidator())
        .Map(order => ProcessOrder(order));
  • methodEnsureValidAsync<T>
    public static async Task<Result<T>> EnsureValidAsync<T>(this Task<Result<T>> resultTask, global::FluentValidation.IValidator<T> validator, CancellationToken cancellationToken = default)

    Integrates validation asynchronously into a Result pipeline.

    resultTask: this Task<Result<T>>
    The task returning the result containing the value to validate.
    validator: global::FluentValidation.IValidator<T>
    The FluentValidation validator.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operation.

    Returns: A task representing the asynchronous operation. The task result contains the original result if valid, or a validation failure result.

    Type parameters: T: The type of the value to validate. Exceptions: InvalidOperationException: The awaited result is an uninitialized default value

  • methodToValidationResult
    public static Result ToValidationResult(this ValidationResult validationResult)

    Converts a `ValidationResult` to a non-generic `Result`. Returns `Result.Success()` if valid, or a structured validation failure if not.

    validationResult: this ValidationResult
    The FluentValidation result to convert.

    Returns: A `Result` representing the validation outcome.

    Example:

    var validator = new OrderValidator();
    var result = validator.Validate(order).ToValidationResult();
    
    return result.Match(
        onSuccess: () => "Valid",
        onFailure: error => $"Invalid: {error.Description}"
    );
  • methodToValidationResult<T>
    public static Result<T> ToValidationResult<T>(this ValidationResult validationResult, T value)

    Converts a `ValidationResult` to a `Result<T>`. Returns `Result.Success<T>(T)` with the provided value if valid, or a structured validation failure if not.

    validationResult: this ValidationResult
    The FluentValidation result to convert.
    value: T
    The value to wrap in the result if validation succeeds.

    Returns: A `Result<T>` representing the validation outcome.

    Type parameters: T: The type of the value to wrap on success. Example:

    var validator = new OrderValidator();
    var result = validator.Validate(order).ToValidationResult(order);
    
    return result.Map(o => ProcessOrder(o));
  • methodValidateToResult<T>
    public static Result ValidateToResult<T>(this global::FluentValidation.IValidator<T> validator, T instance)

    Validates an object using the provided validator and returns a `Result`.

    validator: this global::FluentValidation.IValidator<T>
    The FluentValidation validator.
    instance: T
    The object to validate.

    Returns: A `Result` representing the validation outcome.

    Named `ValidateToResult` instead of `Validate` to avoid method resolution ambiguity with FluentValidation's own `IValidator<T>.Validate(T)` when both the `FluentValidation` and `EricksonLopez.Result.FluentValidation` namespaces are imported. Type parameters: T: The type of the object to validate.

  • methodValidateToResultAsync<T>
    public static async Task<Result> ValidateToResultAsync<T>(this global::FluentValidation.IValidator<T> validator, T instance, CancellationToken cancellationToken = default)

    Validates an object asynchronously and returns a `Result`.

    validator: this global::FluentValidation.IValidator<T>
    The FluentValidation validator.
    instance: T
    The object to validate.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result` representing the validation outcome.

    Named `ValidateToResultAsync` instead of `ValidateAsync` to avoid method resolution ambiguity with FluentValidation's own `IValidator<T>.ValidateAsync(T)`. Type parameters: T: The type of the object to validate.

  • methodValidateToResultWithValue<T>
    public static Result<T> ValidateToResultWithValue<T>(this global::FluentValidation.IValidator<T> validator, T instance)

    Validates an object using the provided validator and returns a `Result<T>` wrapping the validated instance on success.

    validator: this global::FluentValidation.IValidator<T>
    The FluentValidation validator.
    instance: T
    The object to validate.

    Returns: A `Result<T>` wrapping `instance` on success, or a validation failure.

    Type parameters: T: The type of the object to validate.

  • methodValidateToResultWithValueAsync<T>
    public static async Task<Result<T>> ValidateToResultWithValueAsync<T>(this global::FluentValidation.IValidator<T> validator, T instance, CancellationToken cancellationToken = default)

    Validates an object asynchronously and returns a `Result<T>` wrapping the validated instance on success.

    validator: this global::FluentValidation.IValidator<T>
    The FluentValidation validator.
    instance: T
    The object to validate.
    cancellationToken: CancellationToken
    A token that can be used to cancel the validation operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<T>` wrapping `instance` on success, or a validation failure.

    Type parameters: T: The type of the object to validate.

class

SecurityValidationExtensions

Assembly: EricksonLopez.Result.FluentValidation
public static partial class SecurityValidationExtensions

Provides reusable, NativeAOT-compatible FluentValidation security rules protecting against stored XSS HTML injection, PostgreSQL UTF-8 null-byte (`0x00`) crashes, invalid enum casts, and Server-Side Request Forgery (SSRF) against loopback, RFC1918, CGNAT, link-local, and cloud metadata endpoints.

Members (10)

  • methodIsPublicHttpOrHttpsUrl
    public static bool IsPublicHttpOrHttpsUrl(string rawUrl, bool requireHttps = false)

    Evaluates whether `rawUrl` is a syntactically valid, public routable HTTP(S) URL.

    rawUrl: string
    The candidate URL string.
    requireHttps: bool
    Whether `https` is mandatory.

    Returns: `true` if safe and public; otherwise `false`.

  • methodMustBeDefinedEnum<T, TEnum>
    public static IRuleBuilderOptions<T, TEnum> MustBeDefinedEnum<T, TEnum>(this IRuleBuilder<T, TEnum> ruleBuilder) where TEnum : struct, Enum

    Validates that an enum value is a defined member of `TEnum` using NativeAOT-safe generic checks.

    ruleBuilder: this IRuleBuilder<T, TEnum>
    The FluentValidation rule builder.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.; TEnum: The target enum type.

  • methodMustBePublicHttpsOrHttpUrl<T>
    public static IRuleBuilderOptions<T, string?> MustBePublicHttpsOrHttpUrl<T>(this IRuleBuilder<T, string?> ruleBuilder, bool requireHttps = false)

    Validates that a non-empty URL string is an absolute `http` or `https` URI targeting a public routable host.

    ruleBuilder: this IRuleBuilder<T, string?>
    The FluentValidation rule builder.
    requireHttps: bool
    When `true`, strictly requires the `https` scheme.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.

  • methodMustBePublicUrl<T>
    public static IRuleBuilderOptions<T, string?> MustBePublicUrl<T>(this IRuleBuilder<T, string?> ruleBuilder, bool requireHttps = false)

    Validates that a non-empty URL string is an absolute `http` or `https` URI targeting a public routable host (blocking loopback, RFC1918 private networks, RFC6598 CGNAT, cloud link-local metadata `169.254.0.0/16`, IPv6 ULA/link-local, and IPv4-mapped IPv6).

    ruleBuilder: this IRuleBuilder<T, string?>
    The FluentValidation rule builder.
    requireHttps: bool
    When `true`, rejects `http://` URLs and requires `https://`.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.

  • methodMustBeValidEnum<T, TEnum>
    public static IRuleBuilderOptions<T, int> MustBeValidEnum<T, TEnum>(this IRuleBuilder<T, int> ruleBuilder) where TEnum : struct, Enum

    Validates that a 32-bit integer corresponds to a defined member of `TEnum`.

    ruleBuilder: this IRuleBuilder<T, int>
    The FluentValidation rule builder.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.; TEnum: The target enum type.

  • methodMustBeValidEnumName<T, TEnum>
    public static IRuleBuilderOptions<T, string?> MustBeValidEnumName<T, TEnum>(this IRuleBuilder<T, string?> ruleBuilder) where TEnum : struct, Enum

    Validates that a non-empty string parses to a defined member name of `TEnum` (rejecting raw numeric strings).

    ruleBuilder: this IRuleBuilder<T, string?>
    The FluentValidation rule builder.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.; TEnum: The target enum type.

  • methodMustBeValidEnumWhenPresent<T, TEnum>
    public static IRuleBuilderOptions<T, int?> MustBeValidEnumWhenPresent<T, TEnum>(this IRuleBuilder<T, int?> ruleBuilder) where TEnum : struct, Enum

    Validates that a nullable 32-bit integer, when present, corresponds to a defined member of `TEnum`.

    ruleBuilder: this IRuleBuilder<T, int?>
    The FluentValidation rule builder.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.; TEnum: The target enum type.

  • methodMustNotContainHtml<T>
    public static IRuleBuilderOptions<T, string?> MustNotContainHtml<T>(this IRuleBuilder<T, string?> ruleBuilder)

    Rejects strings containing HTML or XML markup tags (`<...>`) to prevent stored XSS. Null or empty strings pass so `NotEmpty()` controls requiredness independently.

    ruleBuilder: this IRuleBuilder<T, string?>
    The FluentValidation rule builder.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.

  • methodMustNotContainHtmlWhenPresent<T>
    public static IRuleBuilderOptions<T, string?> MustNotContainHtmlWhenPresent<T>(this IRuleBuilder<T, string?> ruleBuilder)

    Nullable alias rejecting strings containing HTML or XML markup tags when a value is present.

    ruleBuilder: this IRuleBuilder<T, string?>
    The FluentValidation rule builder.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.

  • methodMustNotContainNullBytes<T>
    public static IRuleBuilderOptions<T, string?> MustNotContainNullBytes<T>(this IRuleBuilder<T, string?> ruleBuilder)

    Rejects strings containing embedded null bytes (`\0`), preventing PostgreSQL `22021` UTF-8 encoding failures and C-string truncation attacks.

    ruleBuilder: this IRuleBuilder<T, string?>
    The FluentValidation rule builder.

    Returns: FluentValidation rule options for chaining.

    Type parameters: T: The validated model type.

EricksonLopez.Result.Generic#

1
struct

Result<TValue, TError>

Assembly: EricksonLopez.Result.Generic
public readonly struct Result<TValue, TError> : IEquatable<Result<TValue, TError>> where TError : class
Implements: IEquatable<Result<TValue, TError>>

Represents a result of an operation that can succeed with a typed value `TValue` or fail with a strongly-typed domain error `TError`.

Remarks:

Type parameters: TValue: The success value type.; TError: The strongly-typed error type.

Members (22)

  • methodBind<TNext>
    public Result<TNext, TError> Bind<TNext>(Func<TValue, Result<TNext, TError>> bind)

    Binds the success value to a new `Result<TNext, TError>`.

    bind: Func<TValue, Result<TNext, TError>>
    The operation to execute with the success value.

    Returns: The result of executing `bind` on success; otherwise, a failure with the original error.

    Type parameters: TNext: The value type of the chained result. Exceptions: ArgumentNullException: `bind` is `null`; InvalidOperationException: The result is uninitialized

  • methodEquals
    public bool Equals(Result<TValue, TError> other)

    Determines whether this result is equal to another result.

    other: Result<TValue, TError>
    The other result to compare against.

    Returns: `true` if both results represent the same outcome; otherwise, `false`.

  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodFailure
    public static Result<TValue, TError> Failure(TError error)

    Creates a failure result containing `error`.

    error: TError
    The strongly-typed error to wrap in the failure result.

    Returns: A failed `Result<TValue, TError>` instance containing `error`.

    Exceptions: ArgumentNullException: `error` is `null`

  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodMap<TNext>
    public Result<TNext, TError> Map<TNext>(Func<TValue, TNext> mapper)

    Projects the success value using `mapper`.

    mapper: Func<TValue, TNext>
    The projection function applied to the success value.

    Returns: A new `Result<TNext, TError>` containing the projected value on success, or the original error on failure.

    Type parameters: TNext: The return type of the mapper function. Exceptions: ArgumentNullException: `mapper` is `null`; InvalidOperationException: The result is uninitialized

  • methodMapError<TNextError>
    public Result<TValue, TNextError> MapError<TNextError>(Func<TError, TNextError> errorMapper) where TNextError : class

    Projects the error type using `errorMapper`.

    errorMapper: Func<TError, TNextError>
    The projection function applied to the failure error.

    Returns: A new `Result<TValue, TNextError>` containing the original value on success, or the projected error on failure.

    Type parameters: TNextError: The target strongly-typed error type. Exceptions: ArgumentNullException: `errorMapper` is `null`; InvalidOperationException: The result is uninitialized

  • methodMatch<TOut>
    public TOut Match<TOut>(Func<TValue, TOut> onSuccess, Func<TError, TOut> onFailure)

    Matches either branch depending on success or failure.

    onSuccess: Func<TValue, TOut>
    The function to evaluate with the value if the result is successful.
    onFailure: Func<TError, TOut>
    The function to evaluate with the error if the result is a failure.

    Returns: The value produced by either `onSuccess` or `onFailure`.

    Type parameters: TOut: The return type produced by the matching functions. Exceptions: ArgumentNullException: `onSuccess` or `onFailure` is `null`; InvalidOperationException: The result is uninitialized

  • methodSuccess
    public static Result<TValue, TError> Success(TValue value)

    Creates a successful result containing `value`.

    value: TValue
    The success value to wrap in the result.

    Returns: A successful `Result<TValue, TError>` instance containing `value`.

  • methodToResult
    public EricksonLopez.Result.Result<TValue> ToResult(Func<TError, EricksonLopez.Result.Error> errorMapper)

    Converts this strongly-typed result to the standard `Result.Result<TValue>` by mapping the generic `TError` to `Result.Error`.

    errorMapper: Func<TError, EricksonLopez.Result.Error>
    The mapping function that converts `TError` to `Result.Error`.

    Returns: A standard `Result.Result<TValue>` representing the outcome.

    Exceptions: ArgumentNullException: `errorMapper` is `null`; InvalidOperationException: The result is uninitialized

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTryGetError
    public bool TryGetError(out TError error)

    Attempts to retrieve the failure error.

    error: out TError
    When this method returns, contains the error if the operation failed; otherwise, `null`.

    Returns: `true` if the operation failed and `error` is populated; otherwise, `false`.

  • methodTryGetValue
    public bool TryGetValue(out TValue value)

    Attempts to retrieve the success value.

    value: out TValue
    When this method returns, contains the success value if the operation succeeded; otherwise, the default value.

    Returns: `true` if the operation succeeded and `value` is populated; otherwise, `false`.

  • methodimplicit operator Result<TValue, TError>
    public static implicit operator Result<TValue, TError>(TError error)

    Converts a strongly-typed error implicitly into a failed `Result<TValue, TError>`.

    error: TError
    The strongly-typed error to wrap in a failed result.
  • methodimplicit operator Result<TValue, TError>
    public static implicit operator Result<TValue, TError>(TValue value)

    Converts a value implicitly into a successful `Result<TValue, TError>`.

    value: TValue
    The value to wrap in a successful result.
  • methodoperator !=
    public static bool operator !=(Result<TValue, TError> left, Result<TValue, TError> right)

    Determines whether two `Result<TValue, TError>` instances are not equal.

    left: Result<TValue, TError>
    The first result to compare.
    right: Result<TValue, TError>
    The second result to compare.

    Returns: `true` if the instances are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(Result<TValue, TError> left, Result<TValue, TError> right)

    Determines whether two `Result<TValue, TError>` instances are equal.

    left: Result<TValue, TError>
    The first result to compare.
    right: Result<TValue, TError>
    The second result to compare.

    Returns: `true` if both instances are equal; otherwise, `false`.

  • propertyError
    public TError Error { get; }

    Gets the strongly-typed failure error.

    Exceptions: InvalidOperationException: The result is a success or uninitialized

  • propertyIsFailure
    public bool IsFailure { get; }

    Gets a value indicating whether the operation failed.

  • propertyIsSuccess
    public bool IsSuccess { get; }

    Gets a value indicating whether the operation succeeded.

  • propertyIsUninitialized
    public bool IsUninitialized { get; }

    Gets a value indicating whether the struct is an uninitialized default value.

  • propertyValue
    public TValue Value { get; }

    Gets the success value.

    Exceptions: InvalidOperationException: The result is a failure or uninitialized

EricksonLopez.Result.Grpc#

3
class

GrpcErrorMapper

Assembly: EricksonLopez.Result.Grpc
public static class GrpcErrorMapper

Provides mapping logic between `Error`, `ErrorType`, and gRPC `StatusCode` and `RpcException`.

Members (3)

  • methodToError
    public static Error ToError(this RpcException rpcException)

    Reconstitutes an `Error` from an `RpcException` inspecting its status and trailers.

    rpcException: this RpcException
    The gRPC exception to map.

    Returns: A domain `Error` instance.

    Exceptions: ArgumentNullException: `rpcException` is `null`

  • methodToRpcException
    public static RpcException ToRpcException(this Error error)

    Converts an `Error` into an `RpcException` with structured metadata trailers.

    error: this Error
    The error to convert.

    Returns: A populated `RpcException`.

    Exceptions: ArgumentNullException: `error` is `null`

  • methodToStatusCode
    public static StatusCode ToStatusCode(this ErrorType errorType)

    Maps a domain `ErrorType` to its canonical gRPC `StatusCode`.

    errorType: this ErrorType
    The error type to convert.

    Returns: The corresponding gRPC status code.

class

GrpcResultExtensions

Assembly: EricksonLopez.Result.Grpc
public static class GrpcResultExtensions

Provides client-side extension methods for converting gRPC call invocations into `Result<TValue>` envelopes without catching raw `RpcException`.

Members (2)

  • methodToResultAsync<TResponse>
    public static async Task<Result<TResponse>> ToResultAsync<TResponse>(this AsyncUnaryCall<TResponse> call)

    Asynchronously awaits a gRPC unary call, returning a successful `Result<TValue>` with the response on completion, or mapping an `RpcException` to a domain error failure.

    call: this AsyncUnaryCall<TResponse>
    The async unary call task.

    Returns: A result containing the response or the mapped error.

    Type parameters: TResponse: The gRPC response message type.

  • methodToResultAsync<TResponse>
    public static async Task<Result<TResponse>> ToResultAsync<TResponse>(this Task<TResponse> responseTask)

    Asynchronously awaits a gRPC response task, returning a successful `Result<TValue>` with the response on completion, or mapping an `RpcException` to a domain error failure.

    responseTask: this Task<TResponse>
    The async response task.

    Returns: A result containing the response or the mapped error.

    Type parameters: TResponse: The gRPC response message type.

class

ResultServerInterceptor

Assembly: EricksonLopez.Result.Grpc
public sealed class ResultServerInterceptor : Interceptor
Inherits: Interceptor

Represents a gRPC server interceptor that inspects handler results and unhandled exceptions, converting domain `Error` failures and exceptions into standardized `RpcException` instances with status codes and metadata trailers.

Members (1)

  • methodUnaryServerHandler<TRequest, TResponse>
    public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation)

    Inherits documentation from base type or interface.

    request: TRequest
    context: ServerCallContext
    continuation: UnaryServerMethod<TRequest, TResponse>

EricksonLopez.Result.MassTransit#

3
class

ResultConsumeFilter<TMessage>

Assembly: EricksonLopez.Result.MassTransit
public sealed class ResultConsumeFilter<TMessage> : IFilter<ConsumeContext<TMessage>> where TMessage : class
Implements: IFilter<ConsumeContext<TMessage>>

Represents a MassTransit consume filter that coordinates domain `Result` outcomes, publishing structured `ResultFault` messages when consumers return or signal domain failures.

Remarks:

Type parameters: TMessage: The consumed message type.

Members (3)

  • constructorResultConsumeFilter
    public ResultConsumeFilter(Func<ConsumeContext<TMessage>, Error, Task>? onFault = null)

    Initializes a new instance of the `ResultConsumeFilter<TMessage>` class.

    onFault: Func<ConsumeContext<TMessage>, Error, Task>?
    An optional custom fault handler delegate.
  • methodProbe
    public void Probe(ProbeContext context)

    Inherits documentation from base type or interface.

    context: ProbeContext
  • methodSend
    public async Task Send(ConsumeContext<TMessage> context, IPipe<ConsumeContext<TMessage>> next)

    Inherits documentation from base type or interface.

    context: ConsumeContext<TMessage>
    next: IPipe<ConsumeContext<TMessage>>
class

ResultConsumePipeConfiguratorExtensions

Assembly: EricksonLopez.Result.MassTransit
public static class ResultConsumePipeConfiguratorExtensions

Provides extension methods for `IConsumePipeConfigurator` to configure Result pattern pipeline filters and fault translation.

Members (1)

  • methodUseResultFilter<TMessage>
    public static void UseResultFilter<TMessage>(this IConsumePipeConfigurator configurator, Func<ConsumeContext<TMessage>, Error, Task>? onFault = null) where TMessage : class

    Configures the consume pipe to execute the `ResultConsumeFilter<TMessage>` for the specified message type.

    configurator: this IConsumePipeConfigurator
    The pipe configurator instance.
    onFault: Func<ConsumeContext<TMessage>, Error, Task>?
    An optional custom fault callback.

    Type parameters: TMessage: The message type to filter.

class

ResultFault

Assembly: EricksonLopez.Result.MassTransit
public sealed class ResultFault

Represents a structured message fault contract published or returned across message transports when a consumer operation yields a domain `Error`.

Members (12)

  • constructorResultFault
    public ResultFault()

    Initializes a new instance of the `ResultFault` class.

  • constructorResultFault
    public ResultFault(Error error)

    Initializes a new instance of the `ResultFault` class from an `Error`.

    error: Error
    The domain error to map.
  • methodFromError
    public static ResultFault FromError(Error error)

    Creates a `ResultFault` instance from a domain `Error`.

    error: Error
    The source error.

    Returns: A mapped fault message.

  • propertyCode
    public string Code { get; set; }

    Gets or sets the unique error code.

  • propertyCorrelationId
    public string? CorrelationId { get; set; }

    Gets or sets the correlation ID.

  • propertyDescription
    public string Description { get; set; }

    Gets or sets the error description.

  • propertyDescriptionKey
    public string? DescriptionKey { get; set; }

    Gets or sets the localization key.

  • propertyMetadata
    public IReadOnlyDictionary<string, object> Metadata { get; set; }

    Gets or sets the structured metadata dictionary.

  • propertyRetryability
    public string Retryability { get; set; }

    Gets or sets the retryability classification name.

  • propertySeverity
    public string Severity { get; set; }

    Gets or sets the severity classification name.

  • propertyTraceId
    public string? TraceId { get; set; }

    Gets or sets the ambient trace ID.

  • propertyType
    public string Type { get; set; }

    Gets or sets the error type name.

EricksonLopez.Result.Maybe#

2
class

MaybeExtensions

Assembly: EricksonLopez.Result.Maybe
public static class MaybeExtensions

Provides asynchronous extension methods for `Maybe<T>`.

Members (3)

  • methodBind<T, TNext>
    public static async Task<Maybe<TNext>> Bind<T, TNext>(this Task<Maybe<T>> maybeTask, Func<T, Task<Maybe<TNext>>> bind, CancellationToken cancellationToken = default)

    Binds the value of a `Task<Maybe<T>>` using `bind`.

    maybeTask: this Task<Maybe<T>>
    The task returning the maybe instance.
    bind: Func<T, Task<Maybe<TNext>>>
    The asynchronous operation to execute with the value if present.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the bound `Maybe<TNext>` if present; otherwise, `Maybe<TNext>.None`.

    Type parameters: T: The source value type.; TNext: The target value type. Exceptions: ArgumentNullException: `maybeTask` or `bind` is `null`; OperationCanceledException: The operation was canceled

  • methodMap<T, TNext>
    public static async Task<Maybe<TNext>> Map<T, TNext>(this Task<Maybe<T>> maybeTask, Func<T, TNext> mapper, CancellationToken cancellationToken = default)

    Projects the value of a `Task<Maybe<T>>` using `mapper`.

    maybeTask: this Task<Maybe<T>>
    The task returning the maybe instance.
    mapper: Func<T, TNext>
    The projection function applied to the value.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `Maybe<TNext>` with the mapped value if present; otherwise, `Maybe<TNext>.None`.

    Type parameters: T: The source value type.; TNext: The projected value type. Exceptions: ArgumentNullException: `maybeTask` or `mapper` is `null`; OperationCanceledException: The operation was canceled

  • methodToResult<T>
    public static async Task<Result<T>> ToResult<T>(this Task<Maybe<T>> maybeTask, Error notFoundError, CancellationToken cancellationToken = default)

    Converts a `Task<Maybe<T>>` to `Task<Result<T>>`.

    maybeTask: this Task<Maybe<T>>
    The task returning the maybe instance.
    notFoundError: Error
    The error to return if no value is present.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a successful `Result<T>` if present; otherwise, a failure with `notFoundError`.

    Type parameters: T: The underlying value type. Exceptions: ArgumentNullException: `maybeTask` or `notFoundError` is `null`; OperationCanceledException: The operation was canceled

struct

Maybe<T>

Assembly: EricksonLopez.Result.Maybe
public readonly struct Maybe<T> : IEquatable<Maybe<T>>
Implements: IEquatable<Maybe<T>>

Represents an optional value of type `T` with zero heap allocation.

Remarks:

Type parameters: T: The underlying value type.

Members (23)

  • methodBind<TNext>
    public Maybe<TNext> Bind<TNext>(Func<T, Maybe<TNext>> bind)

    Binds to another `Maybe<TNext>` if present; otherwise returns `Maybe<TNext>.None`.

    bind: Func<T, Maybe<TNext>>
    The operation to execute with the value if present.

    Returns: The result of executing `bind` if present; otherwise, `Maybe<TNext>.None`.

    Type parameters: TNext: The value type of the chained maybe. Exceptions: ArgumentNullException: `bind` is `null`

  • methodBind<TState, TNext>
    public Maybe<TNext> Bind<TState, TNext>(TState state, Func<TState, T, Maybe<TNext>> bind)

    Binds to another `Maybe<TNext>` with closure-free `state`.

    state: TState
    The state value passed to the bind function.
    bind: Func<TState, T, Maybe<TNext>>
    The operation to execute with state and the value if present.

    Returns: The result of executing `bind` if present; otherwise, `Maybe<TNext>.None`.

    Type parameters: TState: The type of the state object passed to the bind function.; TNext: The value type of the chained maybe. Exceptions: ArgumentNullException: `bind` is `null`

  • methodEnsure
    public Maybe<T> Ensure(Func<T, bool> predicate)

    Filters the value against `predicate`; returns `None` if the predicate fails.

    predicate: Func<T, bool>
    The condition to test on the underlying value.

    Returns: This instance if the condition is met; otherwise, `None`.

    Exceptions: ArgumentNullException: `predicate` is `null`

  • methodEquals
    public bool Equals(Maybe<T> other)

    Determines whether this instance is equal to another `Maybe<T>`.

    other: Maybe<T>
    The other instance to compare against.

    Returns: `true` if both instances represent the same value; otherwise, `false`.

  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodFrom
    public static Maybe<T> From(T? value)

    Creates a `Maybe<T>` containing the specified value, or `None` if `null`.

    value: T?
    The optional value to wrap.

    Returns: A `Maybe<T>` containing `value` if not `null`; otherwise `None`.

  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodGetValueOrDefault
    public T GetValueOrDefault(T defaultValue)

    Returns the underlying value if present; otherwise returns `defaultValue`.

    defaultValue: T
    The fallback value to return if no value is present.

    Returns: The underlying value if present; otherwise, `defaultValue`.

  • methodGetValueOrFallback
    public T GetValueOrFallback(Func<T> fallback)

    Returns the underlying value if present; otherwise invokes `fallback`.

    fallback: Func<T>
    The function generating a fallback value if no value is present.

    Returns: The underlying value if present; otherwise, the value generated by `fallback`.

    Exceptions: ArgumentNullException: `fallback` is `null`

  • methodMap<TNext>
    public Maybe<TNext> Map<TNext>(Func<T, TNext> mapper)

    Maps the value using `mapper` if present; otherwise returns `Maybe<TNext>.None`.

    mapper: Func<T, TNext>
    The projection function applied to the value.

    Returns: A new `Maybe<TNext>` containing the mapped value if present; otherwise, `Maybe<TNext>.None`.

    Type parameters: TNext: The return type of the mapper function. Exceptions: ArgumentNullException: `mapper` is `null`

  • methodMap<TState, TNext>
    public Maybe<TNext> Map<TState, TNext>(TState state, Func<TState, T, TNext> mapper)

    Maps the value with closure-free `state` if present.

    state: TState
    The state value passed to the mapper function.
    mapper: Func<TState, T, TNext>
    The projection function applied to state and the value.

    Returns: A new `Maybe<TNext>` containing the mapped value if present; otherwise, `Maybe<TNext>.None`.

    Type parameters: TState: The type of the state object passed to the mapper.; TNext: The return type of the mapper function. Exceptions: ArgumentNullException: `mapper` is `null`

  • methodMatch<TOut>
    public TOut Match<TOut>(Func<T, TOut> onValue, Func<TOut> onNone)

    Matches either branch depending on whether this instance has a value.

    onValue: Func<T, TOut>
    The function to evaluate with the value if present.
    onNone: Func<TOut>
    The function to evaluate if no value is present.

    Returns: The value produced by either `onValue` or `onNone`.

    Type parameters: TOut: The output type produced by the matching functions. Exceptions: ArgumentNullException: `onValue` or `onNone` is `null`

  • methodToResult
    public Result<T> ToResult(Error notFoundError)

    Converts this `Maybe<T>` to a `Result<T>`, using `notFoundError` if empty.

    notFoundError: Error
    The error to return if no value is present.

    Returns: A successful `Result<T>` containing the value if present; otherwise, a failure with `notFoundError`.

    Exceptions: ArgumentNullException: `notFoundError` is `null`

  • methodToResult
    public Result<T> ToResult(Func<Error> errorFactory)

    Converts this `Maybe<T>` to a `Result<T>`, using `errorFactory` if empty.

    errorFactory: Func<Error>
    A factory that generates the error if no value is present.

    Returns: A successful `Result<T>` containing the value if present; otherwise, a failure with the generated error.

    Exceptions: ArgumentNullException: `errorFactory` is `null`

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTryGetValue
    public bool TryGetValue(out T value)

    Attempts to retrieve the underlying value if present.

    value: out T
    When this method returns, contains the underlying value if present; otherwise, the default value.

    Returns: `true` if this instance contains a value; otherwise, `false`.

  • methodimplicit operator Maybe<T>
    public static implicit operator Maybe<T>(T? value)

    Converts a nullable value implicitly into a `Maybe<T>`.

    value: T?
    The value to wrap.
  • methodoperator !=
    public static bool operator !=(Maybe<T> left, Maybe<T> right)

    Determines whether two `Maybe<T>` instances are not equal.

    left: Maybe<T>
    The first instance to compare.
    right: Maybe<T>
    The second instance to compare.

    Returns: `true` if the instances are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(Maybe<T> left, Maybe<T> right)

    Determines whether two `Maybe<T>` instances are equal.

    left: Maybe<T>
    The first instance to compare.
    right: Maybe<T>
    The second instance to compare.

    Returns: `true` if both instances are equal; otherwise, `false`.

  • propertyHasNoValue
    public bool HasNoValue { get; }

    Gets a value indicating whether this instance does not contain a value.

  • propertyHasValue
    public bool HasValue { get; }

    Gets a value indicating whether this instance contains a value.

  • propertyNone
    public static Maybe<T> None { get; }

    Gets an empty `Maybe<T>` with no value.

  • propertyValue
    public T Value { get; }

    Gets the underlying value if present; otherwise throws an `InvalidOperationException`.

    Exceptions: InvalidOperationException: The instance does not contain a value

EricksonLopez.Result.MediatR#

2
class

ResultExceptionBehavior<TRequest, TResponse>

Assembly: EricksonLopez.Result.MediatR
public sealed class ResultExceptionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
Implements: IPipelineBehavior<TRequest, TResponse>

Represents a MediatR pipeline behavior that catches unhandled exceptions in request handlers and wraps them as `Result` failures instead of propagating the exception.

Remarks:

This behavior intercepts exceptions thrown by inner handlers and converts them into `Result.Failure(Error)` using a configurable error factory. By default, it creates an `ErrorType.Unexpected` error with the exception message. Registration: `services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ResultExceptionBehavior<,>));` Note: This behavior only activates when the response type is `Result` or `Result<T>`. Non-Result responses pass through unmodified. Performance: The failure factory delegate is compiled once per closed generic `TResponse` type and cached statically. Subsequent invocations use the cached delegate with zero reflection overhead. ⚠ NativeAOT / Trimming: Uses `Expression.Lambda.Compile()` and `MakeGenericMethod()` at static initialization to build a cached failure delegate. It requires dynamic code generation and is not compatible with NativeAOT. MediatR itself (`IsAotCompatible=false`) already requires dynamic code, so this package is only intended for reflection-based runtimes. Type parameters: TRequest: The MediatR request type.; TResponse: The response type (must be `Result` or `Result<T>`).

Members (3)

  • constructorResultExceptionBehavior
    public ResultExceptionBehavior()

    Initializes a new instance of the `ResultExceptionBehavior<TRequest, TResponse>` class using the default error factory.

  • constructorResultExceptionBehavior
    public ResultExceptionBehavior(Func<Exception, Error>? errorFactory)

    Initializes a new instance of the `ResultExceptionBehavior<TRequest, TResponse>` class with a custom error factory.

    errorFactory: Func<Exception, Error>?
    Optional factory to create `Error` from an `Exception`. When `null`, uses `Error.Unexpected(string, string)` with the exception type and message.
  • methodHandle
    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    request: TRequest
    next: RequestHandlerDelegate<TResponse>
    cancellationToken: CancellationToken
class

ResultMediatRExtensions

Assembly: EricksonLopez.Result.MediatR
public static class ResultMediatRExtensions

Provides extension methods for registering Result-aware MediatR pipeline behaviors.

Members (1)

  • methodAddResultExceptionBehavior
    public static IServiceCollection AddResultExceptionBehavior(this IServiceCollection services, Func<Exception, Error>? errorFactory = null)

    Adds the `ResultExceptionBehavior<TRequest, TResponse>` pipeline behavior that catches unhandled exceptions and converts them to Result failures.

    services: this IServiceCollection
    The service collection.
    errorFactory: Func<Exception, Error>?
    Optional factory to create `Error` from an `Exception`. When `null`, uses `Error.Unexpected()` with the exception type and message.

    Returns: The service collection for chaining.

    Example:

    builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
    builder.Services.AddResultExceptionBehavior();

EricksonLopez.Result.OpenApi#

1
class

ResultOpenApiExtensions

Assembly: EricksonLopez.Result.OpenApi
public static class ResultOpenApiExtensions

Provides OpenAPI extensions for annotating Minimal API endpoints that return `Result` or `Result<T>`.

Members (3)

  • methodProducesResult
    public static RouteHandlerBuilder ProducesResult(this RouteHandlerBuilder builder, int statusCode = StatusCodes.Status204NoContent)

    Adds success and RFC 9457 ProblemDetails failure metadata for a non-generic `Result`.

    builder: this RouteHandlerBuilder
    The route handler builder.
    statusCode: int
    The success HTTP status code (default: 204 NoContent).

    Returns: The route handler builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

  • methodProducesResult<TResponse>
    public static RouteHandlerBuilder ProducesResult<TResponse>(this RouteHandlerBuilder builder, int statusCode = StatusCodes.Status200OK)

    Adds success and RFC 9457 ProblemDetails failure metadata for a `Result<T>`.

    builder: this RouteHandlerBuilder
    The route handler builder.
    statusCode: int
    The success HTTP status code (default: 200 OK).

    Returns: The route handler builder for chaining.

    Type parameters: TResponse: The success payload type. Exceptions: ArgumentNullException: `builder` is `null`

  • methodProducesResultProblemDetails
    public static RouteHandlerBuilder ProducesResultProblemDetails(this RouteHandlerBuilder builder)

    Adds standard RFC 9457 ProblemDetails failure response metadata (400, 404, 409, 500) to the endpoint.

    builder: this RouteHandlerBuilder
    The route handler builder.

    Returns: The builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

EricksonLopez.Result.OpenTelemetry#

4
class

ResultActivityAsyncExtensions

Assembly: EricksonLopez.Result.OpenTelemetry
public static class ResultActivityAsyncExtensions

Provides asynchronous extension methods for recording `Result` and `Result<T>` outcomes as OpenTelemetry activities and metrics in async pipelines.

Remarks:

These overloads allow chaining `.TraceOutcome()` directly on `Task<Result>` and `Task<Result<T>>` without breaking the fluent async pipeline by awaiting first. Follows the same sync-path optimization pattern as the core `ResultExtensions`: when the task is already completed synchronously, no async state machine is allocated.

Members (12)

  • methodTraceOnFailure
    public static Task<Result> TraceOnFailure(this Task<Result> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOnFailure(in Result, string, Activity?, ResultMetrics?)`.

    resultTask: this Task<Result>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOnFailure
    public static ValueTask<Result> TraceOnFailure(this ValueTask<Result> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOnFailure(in Result, string, Activity?, ResultMetrics?)`.

    resultTask: this ValueTask<Result>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOnFailure<T>
    public static Task<Result<T>> TraceOnFailure<T>(this Task<Result<T>> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOnFailure<T>(in Result<T>, string, Activity?, ResultMetrics?)`.

    resultTask: this Task<Result<T>>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOnFailure<T>
    public static ValueTask<Result<T>> TraceOnFailure<T>(this ValueTask<Result<T>> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOnFailure<T>(in Result<T>, string, Activity?, ResultMetrics?)`.

    resultTask: this ValueTask<Result<T>>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOnSuccess
    public static Task<Result> TraceOnSuccess(this Task<Result> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOnSuccess(in Result, string, Activity?, ResultMetrics?)`.

    resultTask: this Task<Result>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOnSuccess
    public static ValueTask<Result> TraceOnSuccess(this ValueTask<Result> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOnSuccess(in Result, string, Activity?, ResultMetrics?)`.

    resultTask: this ValueTask<Result>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOnSuccess<T>
    public static Task<Result<T>> TraceOnSuccess<T>(this Task<Result<T>> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOnSuccess<T>(in Result<T>, string, Activity?, ResultMetrics?)`.

    resultTask: this Task<Result<T>>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOnSuccess<T>
    public static ValueTask<Result<T>> TraceOnSuccess<T>(this ValueTask<Result<T>> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOnSuccess<T>(in Result<T>, string, Activity?, ResultMetrics?)`.

    resultTask: this ValueTask<Result<T>>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOutcome
    public static Task<Result> TraceOutcome(this Task<Result> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOutcome(in Result, string, Activity?, ResultMetrics?)`.

    resultTask: this Task<Result>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOutcome
    public static ValueTask<Result> TraceOutcome(this ValueTask<Result> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOutcome(in Result, string, Activity?, ResultMetrics?)`.

    resultTask: this ValueTask<Result>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOutcome<T>
    public static Task<Result<T>> TraceOutcome<T>(this Task<Result<T>> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOutcome<T>(in Result<T>, string, Activity?, ResultMetrics?)`.

    resultTask: this Task<Result<T>>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
  • methodTraceOutcome<T>
    public static ValueTask<Result<T>> TraceOutcome<T>(this ValueTask<Result<T>> resultTask, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Inherits documentation from `ResultActivityExtensions.TraceOutcome<T>(in Result<T>, string, Activity?, ResultMetrics?)`.

    resultTask: this ValueTask<Result<T>>
    operationName: string
    targetActivity: Activity?
    metrics: ResultMetrics?
class

ResultActivityExtensions

Assembly: EricksonLopez.Result.OpenTelemetry
public static class ResultActivityExtensions

Provides extension methods for recording `Result` and `Result<T>` outcomes as OpenTelemetry activities.

Remarks:

Tag names follow the OpenTelemetry Semantic Conventions. Standard attribute `error.type` is used per the semconv specification. Library-specific attributes use the `ericksonlopez.result.*` namespace to avoid future conflicts. See https://opentelemetry.io/docs/specs/semconv/attributes-registry/error/ Design Note — Activity annotation vs. span creation: These extension methods annotate the existing ambient `Activity.Current` (or an explicitly-provided activity) rather than creating new child spans. This means your application code is responsible for starting a parent activity (e.g., via ASP.NET Core request middleware or a manually-created `ActivitySource.StartActivity`). This is intentional — the Result library should not create opinionated span boundaries; it should enrich whatever span the application has already decided to create. If you want the `ResultSource` to be visible in your tracing backend, call `tracerProviderBuilder.AddSource(`ActivitySourceName`)` during OTel setup. ⚠️ DOUBLE-COUNTING WARNING: If you register `ResultMetrics` via DI (using `services.AddResultMetrics()`), you MUST pass the DI-resolved instance to the `metrics` parameter of `TraceOutcome`, `TraceOnFailure`, and `TraceOnSuccess`. If you call these methods without the `metrics` parameter, no DI metrics will be recorded. However, if you ALSO call `ResultMetrics.StaticTrackSuccess` or `ResultMetrics.StaticTrackFailure` separately (static mode), both the static and DI meters will emit events, resulting in double-counted metrics. Choose one mode: - DI mode: Use `services.AddResultMetrics()` + pass the instance via the `metrics` parameter. - Static mode: Call `ResultMetrics.StaticTrackSuccess()`/`StaticTrackFailure()` directly without DI.

Members (8)

  • methodTraceOnFailure
    public static Result TraceOnFailure(this in Result result, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Records only a failure outcome to an Activity and updates failure metrics. If the result is successful, no recording occurs.

    result: this in Result
    The result to trace.
    operationName: string
    The name of the operation being traced.
    targetActivity: Activity?
    The activity to record on. Defaults to `Activity.Current` if `null`.
    metrics: ResultMetrics?
    Optional `ResultMetrics` instance for recording metrics. When provided, records failure using the instance meter. When `null`, no metrics are recorded — only the activity tags are set. ⚠️ DI mode: If you use `services.AddResultMetrics()`, you MUST pass the injected `ResultMetrics` instance here, otherwise metrics will be silently omitted: ```csharp // With DI: result.TraceOnFailure("MyOperation", metrics: _metrics); // Without DI (static mode): result.TraceOnFailure("MyOperation"); ResultMetrics.StaticTrackFailure("MyOperation", error.Code, errorType); ```

    Returns: The original `result` instance unchanged.

  • methodTraceOnFailure<T>
    public static Result<T> TraceOnFailure<T>(this in Result<T> result, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Records only a failure outcome to an Activity and updates failure metrics. If the result is successful, no recording occurs.

    result: this in Result<T>
    The result to trace.
    operationName: string
    The name of the operation being traced.
    targetActivity: Activity?
    The activity to record on. Defaults to `Activity.Current` if `null`.
    metrics: ResultMetrics?
    Optional `ResultMetrics` instance for recording metrics. When provided, records failure using the instance meter. When `null`, no metrics are recorded.

    Returns: The original `result` instance unchanged.

    Type parameters: T: The value type of the result.

  • methodTraceOnSuccess
    public static Result TraceOnSuccess(this in Result result, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Records only a success outcome to an Activity and updates success metrics. If the result is a failure, no recording occurs.

    result: this in Result
    The result to trace.
    operationName: string
    The name of the operation being traced.
    targetActivity: Activity?
    The activity to record on. Defaults to `Activity.Current` if `null`.
    metrics: ResultMetrics?
    Optional `ResultMetrics` instance for recording metrics. When provided, records success using the instance meter. When `null`, no metrics are recorded — only the activity tags are set. ⚠️ DI mode: If you use `services.AddResultMetrics()`, you MUST pass the injected `ResultMetrics` instance here, otherwise success metrics will be silently omitted: ```csharp // With DI — metrics ARE recorded: result.TraceOnSuccess("MyOperation", metrics: _metrics); // Without metrics param — metrics are NOT recorded (activity tags only): result.TraceOnSuccess("MyOperation"); ``` Prefer `TraceOutcome(in Result, string, Activity?, ResultMetrics?)` when you want both success and failure to be recorded in a single call.

    Returns: The original `result` instance unchanged.

  • methodTraceOnSuccess<T>
    public static Result<T> TraceOnSuccess<T>(this in Result<T> result, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Records only a success outcome to an Activity and updates success metrics. If the result is a failure, no recording occurs.

    result: this in Result<T>
    The result to trace.
    operationName: string
    The name of the operation being traced.
    targetActivity: Activity?
    The activity to record on. Defaults to `Activity.Current` if `null`.
    metrics: ResultMetrics?
    Optional `ResultMetrics` instance for recording metrics. When provided, records success using the instance meter. When `null`, no metrics are recorded.

    Returns: The original `result` instance unchanged.

    Type parameters: T: The value type of the result.

  • methodTraceOutcome
    public static Result TraceOutcome(this in Result result, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Records the result outcome (success or failure) to an Activity and updates metrics. For failure, sets activity status to Error and records error attributes. For success, sets activity status to Ok and records success metrics.

    result: this in Result
    The result to trace.
    operationName: string
    The name of the operation being traced.
    targetActivity: Activity?
    The activity to record on. Defaults to `Activity.Current` if `null`.
    metrics: ResultMetrics?
    Optional `ResultMetrics` instance for recording metrics. When provided, records success or failure using the instance meter. When `null`, no metrics are recorded. To use the static (non-DI) meter, call `ResultMetrics.StaticTrackSuccess` / `ResultMetrics.StaticTrackFailure` explicitly after tracing.

    Returns: The original `result` instance unchanged.

  • methodTraceOutcome<T>
    public static Result<T> TraceOutcome<T>(this in Result<T> result, string operationName, Activity? targetActivity = null, ResultMetrics? metrics = null)

    Records the result outcome (success or failure) to an Activity and updates metrics. For failure, sets activity status to Error and records error attributes. For success, sets activity status to Ok and records success metrics.

    result: this in Result<T>
    The result to trace.
    operationName: string
    The name of the operation being traced.
    targetActivity: Activity?
    The activity to record on. Defaults to `Activity.Current` if `null`.
    metrics: ResultMetrics?
    Optional `ResultMetrics` instance for recording metrics. When provided, records success or failure using the instance meter. When `null`, no metrics are recorded — only the activity tags are set. ⚠️ DI mode: If you use `services.AddResultMetrics()`, you MUST pass the injected `ResultMetrics` instance here, otherwise metrics will be silently omitted: ```csharp // With DI — both tracing and metrics are recorded: result.TraceOutcome("MyOperation", metrics: _metrics); // Without metrics param — only activity tags are set, metrics are NOT recorded: result.TraceOutcome("MyOperation"); ```

    Returns: The original `result` instance unchanged.

    Type parameters: T: The value type of the result.

  • fieldActivitySourceName
    public const string ActivitySourceName

    Specifies the name of the ActivitySource identifying Result tracing operations.

    Register this source with your OpenTelemetry TracerProvider: `tracerProviderBuilder.AddSource(ResultActivityExtensions.ActivitySourceName);`

  • fieldResultSource
    public static readonly ActivitySource ResultSource

    Gets the `ActivitySource` for creating Result-related spans. Primarily used to allow OpenTelemetry to subscribe to this source via `tracerProviderBuilder.AddSource(`ActivitySourceName`)`. Application code annotates the existing `Activity.Current` via the `TraceOutcome` / `TraceOnFailure` / `TraceOnSuccess` extension methods.

class

ResultMetrics

Assembly: EricksonLopez.Result.OpenTelemetry
public sealed class ResultMetrics : IDisposable
Implements: IDisposable

Provides OpenTelemetry metrics instrumentation for Result outcomes.

Remarks:

Supports two usage modes: - DI mode (recommended): Construct with a `Meter` provided by your DI container (e.g., via `IMeterFactory` in Microsoft.Extensions.Diagnostics). The caller is responsible for disposing the meter. Call `services.AddResultMetrics()` for automatic registration. - Static mode: Call `StaticTrackSuccess` / `StaticTrackFailure` directly. This uses an internal static `Meter` that is lazily initialized and never disposed. Static mode is suitable for simple scenarios without DI. Important: Do NOT mix both modes simultaneously. If you use DI-managed `ResultMetrics` and also call the `TraceOutcome` / `TraceOnFailure` / `TraceOnSuccess` extension methods without passing the instance via the `metrics` parameter, both the static and DI meters will emit events, resulting in double-counting. Always pass the DI instance to extension methods when using DI mode.

Members (7)

  • constructorResultMetrics
    public ResultMetrics(Meter meter, bool ownsMeter = true)

    Initializes a new instance of the `ResultMetrics` class using an externally provided `Meter`.

    meter: Meter
    The meter to create instruments on. Typically obtained from an `IMeterFactory` in DI.
    ownsMeter: bool
    When `true` (default), this instance will dispose `meter` when `Dispose` is called. Set to `true` when you create the meter yourself (e.g., `new Meter(...)`) and want `ResultMetrics` to manage its lifetime via `using var`. When `false`, the caller retains ownership of the meter. Leave `false` when the meter is provided by `IMeterFactory` in DI — the factory manages the meter lifecycle automatically. See `AddResultMetrics()` for the DI registration.

    Exceptions: ArgumentNullException: `meter` is `null`; InvalidOperationException: DI mode cannot be initialized because static mode is already active

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodStaticTrackFailure
    public static void StaticTrackFailure(string operationName, string errorCode, string errorType)

    Records a failure outcome using the static (non-DI) meter. Consistent naming with the instance `TrackFailure(string, string, string)` method.

    operationName: string
    The name of the operation being recorded.
    errorCode: string
    The application error code associated with the failure.
    errorType: string
    The string representation of the error type.

    This is the primary API for scenarios without a DI container: console apps, AWS Lambda, Azure Functions v1, test harnesses, and other non-hosted environments. For applications using `Microsoft.Extensions.DependencyInjection`, prefer `services.AddResultMetrics()` and injecting the `ResultMetrics` instance to avoid double-counting when both static and DI modes are active simultaneously. ⚠️ CARDINALITY WARNING: The `errorCode` parameter is recorded as a metric tag dimension (`ericksonlopez.result.error.code`). If error codes are high-cardinality (e.g., contain user IDs, request IDs, or record IDs), your metrics backend (Prometheus, OTLP, Azure Monitor) will create a distinct time series for each unique value, potentially causing a metrics explosion. Ensure error codes are low-cardinality bounded enumerations (e.g., `"NOT_FOUND"`, `"VALIDATION_ERROR"`), not per-request identifiers. Testing: When using static methods in unit tests, call `ResetStaticMeterForTesting` in your test cleanup (e.g., `Dispose` or `[AssemblyCleanup]`) to prevent meter state from leaking across test runs. Exceptions: InvalidOperationException: DI mode is already active

  • methodStaticTrackSuccess
    public static void StaticTrackSuccess(string operationName)

    Records a success outcome using the static (non-DI) meter. Consistent naming with the instance `TrackSuccess(string)` method.

    operationName: string
    The name of the operation being recorded.

    This is the primary API for scenarios without a DI container: console apps, AWS Lambda, Azure Functions v1, test harnesses, and other non-hosted environments. Uses a static meter that is lazily initialized and never disposed (standard pattern for ambient OpenTelemetry singletons). For applications using `Microsoft.Extensions.DependencyInjection`, prefer `services.AddResultMetrics()` and injecting the `ResultMetrics` instance to avoid double-counting when both static and DI modes are active simultaneously. Testing: When using static methods in unit tests, call `ResetStaticMeterForTesting` in your test cleanup (e.g., `Dispose` or `[AssemblyCleanup]`) to prevent meter state from leaking across test runs. Exceptions: InvalidOperationException: DI mode is already active

  • methodTrackFailure
    public void TrackFailure(string operationName, string errorCode, string errorType)

    Records a failure outcome using the instance meter.

    operationName: string
    The name of the operation being recorded.
    errorCode: string
    The application error code associated with the failure.
    errorType: string
    The string representation of the error type.

    ⚠️ CARDINALITY WARNING: The `errorCode` parameter is recorded as a metric tag dimension (`ericksonlopez.result.error.code`). Ensure error codes are low-cardinality bounded enumerations, not per-request identifiers such as user IDs or record IDs. High-cardinality values will cause a metrics explosion in your backend (Prometheus, OTLP, Azure Monitor). Exceptions: ObjectDisposedException: This instance has been disposed

  • methodTrackSuccess
    public void TrackSuccess(string operationName)

    Records a success outcome using the instance meter.

    operationName: string
    The name of the operation being recorded.

    Exceptions: ObjectDisposedException: This instance has been disposed

  • fieldMeterName
    public const string MeterName

    Gets the OpenTelemetry Meter name for all Result metrics.

class

ResultServiceCollectionExtensions

Assembly: EricksonLopez.Result.OpenTelemetry
public static class ResultServiceCollectionExtensions

Provides extension methods for configuring Result OpenTelemetry integrations in an `IServiceCollection`.

Members (1)

  • methodAddResultMetrics
    public static IServiceCollection AddResultMetrics(this IServiceCollection services)

    Adds `ResultMetrics` as a singleton to the service collection, integrating it with the application's `IMeterFactory`.

    services: this IServiceCollection
    The service collection.

    Returns: The original service collection for chaining.

    The `Meter` is created via `IMeterFactory` and is disposed automatically when the host disposes the DI container. `ResultMetrics.Dispose` is a no-op for the meter itself when registered this way (`ownsMeter: false`). Do NOT also call the static `ResultMetrics.StaticTrackSuccess` / `ResultMetrics.StaticTrackFailure` methods in the same application — that would cause double-counting via two separate meters. Exceptions: ArgumentNullException: `services` is `null`

EricksonLopez.Result.Polly#

2
class

PollyResultExtensions

Assembly: EricksonLopez.Result.Polly
public static class PollyResultExtensions

Provides execution and composition extension methods on `ResiliencePipeline` and `ResiliencePipeline<T>` for executing monadic pipelines returning `Result` and `Result<TValue>`.

Members (7)

  • methodExecuteResult
    public static Result ExecuteResult(this ResiliencePipeline pipeline, Func<Result> callback)

    Executes the specified non-generic callback through the resilience pipeline.

    pipeline: this ResiliencePipeline
    The resilience pipeline.
    callback: Func<Result>
    The callback to execute.

    Returns: The executed `Result`.

  • methodExecuteResult<T, TState>
    public static Result<T> ExecuteResult<T, TState>(this ResiliencePipeline pipeline, TState state, Func<TState, Result<T>> callback)

    Executes the specified callback through the resilience pipeline with state to avoid closure allocation.

    pipeline: this ResiliencePipeline
    The resilience pipeline.
    state: TState
    The state instance.
    callback: Func<TState, Result<T>>
    The callback to execute.

    Returns: The executed `Result<TValue>`.

    Type parameters: T: The result value type.; TState: The state type passed to the callback.

  • methodExecuteResult<T>
    public static Result<T> ExecuteResult<T>(this ResiliencePipeline pipeline, Func<Result<T>> callback)

    Executes the specified callback through the resilience pipeline.

    pipeline: this ResiliencePipeline
    The resilience pipeline.
    callback: Func<Result<T>>
    The callback to execute.

    Returns: The executed `Result<TValue>`.

    Type parameters: T: The result value type.

  • methodExecuteResult<TState>
    public static Result ExecuteResult<TState>(this ResiliencePipeline pipeline, TState state, Func<TState, Result> callback)

    Executes the specified non-generic callback through the resilience pipeline with state to avoid closure allocation.

    pipeline: this ResiliencePipeline
    The resilience pipeline.
    state: TState
    The state instance.
    callback: Func<TState, Result>
    The callback to execute.

    Returns: The executed `Result`.

    Type parameters: TState: The state type passed to the callback.

  • methodExecuteResultAsync
    public static ValueTask<Result> ExecuteResultAsync(this ResiliencePipeline pipeline, Func<CancellationToken, ValueTask<Result>> callback, CancellationToken cancellationToken = default)

    Asynchronously executes the specified non-generic callback through the resilience pipeline.

    pipeline: this ResiliencePipeline
    The resilience pipeline.
    callback: Func<CancellationToken, ValueTask<Result>>
    The asynchronous callback to execute.
    cancellationToken: CancellationToken
    A cancellation token.

    Returns: A value task containing the executed `Result`.

  • methodExecuteResultAsync<T>
    public static ValueTask<Result<T>> ExecuteResultAsync<T>(this ResiliencePipeline pipeline, Func<CancellationToken, ValueTask<Result<T>>> callback, CancellationToken cancellationToken = default)

    Asynchronously executes the specified callback through the resilience pipeline.

    pipeline: this ResiliencePipeline
    The resilience pipeline.
    callback: Func<CancellationToken, ValueTask<Result<T>>>
    The asynchronous callback to execute.
    cancellationToken: CancellationToken
    A cancellation token.

    Returns: A value task containing the executed `Result<TValue>`.

    Type parameters: T: The result value type.

  • methodExecuteResultAsync<T>
    public static ValueTask<Result<T>> ExecuteResultAsync<T>(this ResiliencePipeline<Result<T>> pipeline, Func<CancellationToken, ValueTask<Result<T>>> callback, CancellationToken cancellationToken = default)

    Asynchronously executes the specified generic resilience pipeline callback.

    pipeline: this ResiliencePipeline<Result<T>>
    The generic resilience pipeline.
    callback: Func<CancellationToken, ValueTask<Result<T>>>
    The asynchronous callback to execute.
    cancellationToken: CancellationToken
    A cancellation token.

    Returns: A value task containing the executed `Result<TValue>`.

    Type parameters: T: The result value type.

class

ResultResilienceStrategyBuilderExtensions

Assembly: EricksonLopez.Result.Polly
public static class ResultResilienceStrategyBuilderExtensions

Provides extension methods for `ResiliencePipelineBuilder` and `PredicateBuilder` to configure retry and resilience strategies tailored for `Result` and `Result<TValue>`.

Members (4)

  • methodAddResultRetry
    public static ResiliencePipelineBuilder<Result> AddResultRetry(this ResiliencePipelineBuilder<Result> builder, int maxRetryAttempts = 3, TimeSpan? delay = null)

    Adds a retry strategy to the pipeline configured to retry when an operation returns a failed `Result` with `ErrorRetryability.Transient`.

    builder: this ResiliencePipelineBuilder<Result>
    The resilience pipeline builder.
    maxRetryAttempts: int
    The maximum number of retry attempts. Defaults to 3.
    delay: TimeSpan?
    The delay between retries. If `null`, a default constant delay is applied.

    Returns: The resilience pipeline builder with the retry strategy configured.

    Exceptions: ArgumentNullException: `builder` is `null`

  • methodAddResultRetry<T>
    public static ResiliencePipelineBuilder<Result<T>> AddResultRetry<T>(this ResiliencePipelineBuilder<Result<T>> builder, int maxRetryAttempts = 3, TimeSpan? delay = null)

    Adds a retry strategy to the pipeline configured to retry when an operation returns a failed `Result<TValue>` with `ErrorRetryability.Transient`.

    builder: this ResiliencePipelineBuilder<Result<T>>
    The resilience pipeline builder.
    maxRetryAttempts: int
    The maximum number of retry attempts. Defaults to 3.
    delay: TimeSpan?
    The delay between retries. If `null`, a default constant delay is applied.

    Returns: The resilience pipeline builder with the retry strategy configured.

    Type parameters: T: The result value type. Exceptions: ArgumentNullException: `builder` is `null`

  • methodHandleRetryableError
    public static PredicateBuilder<Result> HandleRetryableError(this PredicateBuilder<Result> predicateBuilder)

    Configures a predicate that matches any failed `Result` whose error has `ErrorRetryability.Transient`.

    predicateBuilder: this PredicateBuilder<Result>
    The predicate builder instance.

    Returns: The predicate builder configured for retryable errors.

    Exceptions: ArgumentNullException: `predicateBuilder` is `null`

  • methodHandleRetryableError<T>
    public static PredicateBuilder<Result<T>> HandleRetryableError<T>(this PredicateBuilder<Result<T>> predicateBuilder)

    Configures a predicate that matches any failed `Result<TValue>` whose error has `ErrorRetryability.Transient`.

    predicateBuilder: this PredicateBuilder<Result<T>>
    The predicate builder instance.

    Returns: The predicate builder configured for retryable errors.

    Type parameters: T: The result value type. Exceptions: ArgumentNullException: `predicateBuilder` is `null`

EricksonLopez.Result.Serialization#

4
class

ErrorJsonConverter

Assembly: EricksonLopez.Result.Serialization
public sealed class ErrorJsonConverter : JsonConverter<Error>
Inherits: JsonConverter<Error>

Represents an AOT-compliant `JsonConverter<T>` for `Error`. Uses manual property matching and switch-based enum parsing to avoid reflection in NativeAOT scenarios.

Remarks:

Metadata round-trip is partially lossy. Values stored in `Error.Metadata` are serialized preserving native JSON types: numbers (`int`, `long`, `double`, etc.) are written as JSON numbers, booleans as JSON booleans, strings as JSON strings, and collections as JSON arrays. On deserialization, numbers are recovered as `long` or `double`, booleans as `bool`, and all other values (including `DateTime`, `Guid`, custom objects) are deserialized as `string`. The original CLR numeric type (e.g., `int` vs `long`) may differ. If you require type-faithful metadata round-tripping, store metadata as a typed DTO and use a separate property on your domain object rather than relying on `Error.Metadata`.

Members (3)

  • methodRead
    public override Error Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    reader: ref Utf8JsonReader
    typeToConvert: Type
    options: JsonSerializerOptions
  • methodWrite
    public override void Write(Utf8JsonWriter writer, Error value, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    writer: Utf8JsonWriter
    value: Error
    options: JsonSerializerOptions
  • fieldMaxAllowedDepth
    public const int MaxAllowedDepth

    Gets the maximum allowed recursion depth to prevent stack overflow denial-of-service.

class

ResultJsonConverter

Assembly: EricksonLopez.Result.Serialization
public sealed class ResultJsonConverter : JsonConverter<Result>
Inherits: JsonConverter<Result>

Represents a `JsonConverter<T>` for non-generic `Result` instances.

Remarks:

Uses manual `Utf8JsonReader` traversal with case-insensitive property matching, consistent with `ErrorJsonConverter`. This avoids heap-allocating a `JsonDocument` and ensures interoperability with JSON produced by systems using PascalCase or camelCase naming. The `isFailure` property is accepted during deserialization for backward compatibility but is not required.

Members (2)

  • methodRead
    public override Result Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    reader: ref Utf8JsonReader
    typeToConvert: Type
    options: JsonSerializerOptions
  • methodWrite
    public override void Write(Utf8JsonWriter writer, Result value, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    writer: Utf8JsonWriter
    value: Result
    options: JsonSerializerOptions
class

ResultJsonSerializerContext

Assembly: EricksonLopez.Result.Serialization
public partial class ResultJsonSerializerContext : JsonSerializerContext
Inherits: JsonSerializerContext

Provides a source-generated JSON serialization context for Result types.

Members (0)

This type declares 0 public members (e.g. marker interface or empty enum/record).

class

ResultOfTJsonConverter<T>

Assembly: EricksonLopez.Result.Serialization
public sealed class ResultOfTJsonConverter<T> : JsonConverter<Result<T>>
Inherits: JsonConverter<Result<T>>

Represents a `JsonConverter<T>` for generic `Result<T>` instances.

Remarks:

Uses manual `Utf8JsonReader` traversal with case-insensitive property matching, consistent with `ErrorJsonConverter`. The `isFailure` property is accepted during deserialization for backward compatibility but is not required. NativeAOT / Trimming — two construction modes: - Reflection-based (default): `new ResultOfTJsonConverter<MyDto>()` — uses `JsonSerializer.Deserialize<TValue>(ref Utf8JsonReader, JsonSerializerOptions)`. Requires `T` to be preserved by trimming and registered in a `Serialization.JsonSerializerContext` for NativeAOT. - AOT-safe: `new ResultOfTJsonConverter<MyDto>(MyContext.Default.MyDto)` — uses `JsonSerializer.Deserialize<TValue>(ref Utf8JsonReader, JsonTypeInfo<TValue>)`. No reflection, fully compatible with NativeAOT and aggressive trimming. Recommended for all NativeAOT applications. Type parameters: T: The result value type.

Members (4)

  • constructorResultOfTJsonConverter
    public ResultOfTJsonConverter()

    Initializes a new instance of the `ResultOfTJsonConverter<T>` class using reflection-based serialization.

    For NativeAOT or trimmed applications, use `ResultOfTJsonConverter<T>(JsonTypeInfo<T>)` instead.

  • constructorResultOfTJsonConverter
    public ResultOfTJsonConverter(JsonTypeInfo<T> typeInfo)

    Initializes a new instance of the `ResultOfTJsonConverter<T>` class using the specified `JsonTypeInfo<T>`.

    typeInfo: JsonTypeInfo<T>
    The compile-time generated type info for `T`, typically obtained from a `Serialization.JsonSerializerContext` (e.g., `MyAppJsonContext.Default.MyDto`). This overload requires no reflection and is safe for NativeAOT and aggressive trimming.

    Exceptions: ArgumentNullException: `typeInfo` is `null` Example:

    // Preferred AOT-safe registration:
    options.Converters.Add(new ResultOfTJsonConverter<MyDto>(MyAppJsonContext.Default.MyDto));
  • methodRead
    public override Result<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    reader: ref Utf8JsonReader
    typeToConvert: Type
    options: JsonSerializerOptions
  • methodWrite
    public override void Write(Utf8JsonWriter writer, Result<T> value, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    writer: Utf8JsonWriter
    value: Result<T>
    options: JsonSerializerOptions

EricksonLopez.Result.Serialization.Generators#

1
class

ResultJsonConverterGenerator

Assembly: EricksonLopez.Result.Serialization.Generators
public sealed class ResultJsonConverterGenerator : IIncrementalGenerator
Implements: IIncrementalGenerator

Represents an incremental source generator that scans for `[JsonSerializable(typeof(Result<T>))]` attributes on `JsonSerializerContext` subclasses and generates a companion extension method that registers the required `ResultOfTJsonConverter<T>` instances — eliminating the reflection-based `MakeGenericType` + `Activator.CreateInstance` in `ResultJsonConverterFactory`.

Remarks:

Usage: Consumers add `[JsonSerializable(typeof(Result<MyDto>))]` to their `JsonSerializerContext` subclass and this generator produces:

public static class MyContextResultExtensions
{
    public static JsonSerializerOptions AddResultConverters(this JsonSerializerOptions options)
    {
        options.Converters.Add(new ResultJsonConverter());
        options.Converters.Add(new ErrorJsonConverter());
        options.Converters.Add(new ResultOfTJsonConverter<MyDto>());
        return options;
    }
}

Members (1)

  • methodInitialize
    public void Initialize(IncrementalGeneratorInitializationContext context)

    Inherits documentation from base type or interface.

    context: IncrementalGeneratorInitializationContext

EricksonLopez.Result.Testing#

3
class

ErrorAssertions

Assembly: EricksonLopez.Result.Testing
public static class ErrorAssertions

Provides fluent assertion extensions directly on `Error` instances.

Remarks:

Example: Enables chained assertions after `ResultAssertions.ShouldBeFailure`:

result.ShouldBeFailure()
      .ShouldHaveErrorCode("Order.Expired")
      .ShouldHaveErrorType(ErrorType.Domain)
      .ShouldHaveSeverity(ErrorSeverity.Warning)
      .ShouldHaveMetadata("orderId", expectedId);

Members (14)

  • methodShouldBePermanent
    public static Error ShouldBePermanent(this Error error)

    Asserts that the Error is permanent (not retryable).

    error: this Error
    The error to assert on.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The error retryability is not Permanent

  • methodShouldBeRetryable
    public static Error ShouldBeRetryable(this Error error)

    Asserts that the Error is retryable (Transient).

    error: this Error
    The error to assert on.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The error retryability is not Transient

  • methodShouldContainInnerError
    public static Error ShouldContainInnerError(this Error error, string errorCode)

    Asserts that the Error has at least one inner error with the specified error code.

    error: this Error
    The error to assert on.
    errorCode: string
    The error code to search for among inner errors.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: No inner error with `errorCode` was found

  • methodShouldHaveCorrelationId
    public static Error ShouldHaveCorrelationId(this Error error, string expectedCorrelationId)

    Asserts that the Error has the expected CorrelationId.

    error: this Error
    The error to assert on.
    expectedCorrelationId: string
    The expected correlation ID string.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The correlation ID does not match `expectedCorrelationId`

  • methodShouldHaveDescription
    public static Error ShouldHaveDescription(this Error error, string expectedDescription)

    Asserts that the Error has the expected description.

    error: this Error
    The error to assert on.
    expectedDescription: string
    The expected error description string.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The description does not match `expectedDescription`

  • methodShouldHaveErrorCode
    public static Error ShouldHaveErrorCode(this Error error, string expectedErrorCode)

    Asserts that the Error has the expected error code.

    error: this Error
    The error to assert on.
    expectedErrorCode: string
    The expected error code string.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The error code does not match `expectedErrorCode`

  • methodShouldHaveErrorType
    public static Error ShouldHaveErrorType(this Error error, ErrorType expectedType)

    Asserts that the Error has the expected `ErrorType`.

    error: this Error
    The error to assert on.
    expectedType: ErrorType
    The expected error type.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The error type does not match `expectedType`

  • methodShouldHaveInnerErrors
    public static Error ShouldHaveInnerErrors(this Error error, int expectedCount)

    Asserts that the Error has inner errors of the expected count.

    error: this Error
    The error to assert on.
    expectedCount: int
    The expected number of inner errors.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The inner error count does not match `expectedCount`

  • methodShouldHaveMetadata
    public static Error ShouldHaveMetadata(this Error error, string key, object expectedValue)

    Asserts that the Error contains a metadata entry with the specified key and value.

    error: this Error
    The error to assert on.
    key: string
    The metadata key to look up.
    expectedValue: object
    The expected value corresponding to `key`.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The metadata key was not found or its value does not match `expectedValue`

  • methodShouldHaveMetadataKey
    public static Error ShouldHaveMetadataKey(this Error error, string key)

    Asserts that the Error contains a metadata entry with the specified key.

    error: this Error
    The error to assert on.
    key: string
    The metadata key to check for presence.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The metadata key was not found

  • methodShouldHaveNoInnerErrors
    public static Error ShouldHaveNoInnerErrors(this Error error)

    Asserts that the Error has no inner errors.

    error: this Error
    The error to assert on.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The error contains inner errors

  • methodShouldHaveRetryability
    public static Error ShouldHaveRetryability(this Error error, ErrorRetryability expectedRetryability)

    Asserts that the Error has the expected `ErrorRetryability`.

    error: this Error
    The error to assert on.
    expectedRetryability: ErrorRetryability
    The expected error retryability.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The retryability does not match `expectedRetryability`

  • methodShouldHaveSeverity
    public static Error ShouldHaveSeverity(this Error error, ErrorSeverity expectedSeverity)

    Asserts that the Error has the expected `ErrorSeverity`.

    error: this Error
    The error to assert on.
    expectedSeverity: ErrorSeverity
    The expected error severity.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The severity does not match `expectedSeverity`

  • methodShouldHaveTraceId
    public static Error ShouldHaveTraceId(this Error error, string expectedTraceId)

    Asserts that the Error has the expected OpenTelemetry TraceId.

    error: this Error
    The error to assert on.
    expectedTraceId: string
    The expected trace ID string.

    Returns: The same `error` instance for method chaining.

    Exceptions: ResultAssertionException: The trace ID does not match `expectedTraceId`

class

ResultAssertionException

Assembly: EricksonLopez.Result.Testing
public class ResultAssertionException : Exception
Inherits: Exception

Represents an exception thrown when a Result assertion fails.

Remarks:

This exception inherits from `Exception` rather than a test framework-specific assertion exception (e.g., xUnit's `XunitException`) to avoid coupling to a specific test framework. Test runners such as xUnit, NUnit, and MSTest will display this as a test failure in the output, though it may appear in the "Error" column rather than "Failure" for some runners. Framework integration: To use xUnit-native exceptions (which show as "Failure" instead of "Error" in xUnit output), install the `EricksonLopez.Result.Testing.XUnit` package and call `ResultXUnitAssertionConfig.UseXUnitExceptions()` in your test assembly setup. CA1032: All standard Exception constructors are implemented.

Members (4)

  • constructorResultAssertionException
    public ResultAssertionException()

    Initializes a new instance of the `ResultAssertionException` class with a default message.

  • constructorResultAssertionException
    public ResultAssertionException(string message)

    Initializes a new instance of the `ResultAssertionException` class with a specified error message.

    message: string
    The error message that explains the assertion failure.
  • constructorResultAssertionException
    public ResultAssertionException(string message, Exception innerException)

    Initializes a new instance of the `ResultAssertionException` class with a specified error message and a reference to the inner exception that is the cause of this exception.

    message: string
    The error message that explains the assertion failure.
    innerException: Exception
    The exception that caused this assertion failure.
  • propertyExceptionFactory
    public static Func<string, Exception> ExceptionFactory { get; set; }

    Gets or sets the factory function used to create assertion exceptions. Override this to produce framework-native exceptions (e.g., xUnit's XunitException). Thread-safe: uses `Interlocked` for atomic access.

    Do not call this directly. Use `ResultXUnitAssertionConfig.UseXUnitExceptions()` from the `EricksonLopez.Result.Testing.XUnit` package, or the equivalent for your test framework. Exceptions: ArgumentNullException: The assigned value is `null`

class

ResultAssertions

Assembly: EricksonLopez.Result.Testing
public static class ResultAssertions

Provides fluent testing assertion extensions for `Result` and `Result<T>`.

Members (140)

  • methodShouldBeCombinedFailure
    public static Error ShouldBeCombinedFailure(this in Result result, int expectedErrorCount, string? message = null)

    Asserts that the Result is a failure produced by `Result.Combine(ReadOnlySpan<Result>)` (or equivalent) and that the root error contains exactly `expectedErrorCount` inner errors.

    result: this in Result
    The result to inspect.
    expectedErrorCount: int
    The expected number of combined failures (inner errors).
    message: string?
    Optional custom failure message.

    Returns: The root error with its inner errors.

    A combined failure is identified by its root error code being `WellKnownErrors.CombinedFailuresCode` (typically `"Result.Combine.Failures"`). If you expect a failure from `Combine` but the result has a different code (e.g., only one operation failed so it returned a direct failure), this assertion will also fail to guide you toward the correct assertion. Example:

    var result = Result.Combine(op1, op2, op3);
    var error = result.ShouldBeCombinedFailure(2); // exactly 2 of 3 operations failed
  • methodShouldBeCombinedFailure<T>
    public static Error ShouldBeCombinedFailure<T>(this in Result<T> result, int expectedErrorCount, string? message = null)

    Asserts that the Result<T> is a combined failure with exactly `expectedErrorCount` inner errors.

    result: this in Result<T>
    The result to inspect.
    expectedErrorCount: int
    The expected number of combined failures (inner errors).
    message: string?
    Optional custom failure message.

    Returns: The root error with its inner errors.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure, is not a combined failure, or the inner error count does not match `expectedErrorCount`

  • methodShouldBeCombinedFailureAsync
    public static Task<Error> ShouldBeCombinedFailureAsync(this Task<Result> task, int expectedErrorCount, string? message = null)

    Asserts that the `Task<Result>` is a combined failure with the expected inner error count.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedErrorCount: int
    The expected number of combined failures (inner errors).
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the root error with its inner errors.

  • methodShouldBeCombinedFailureAsync
    public static ValueTask<Error> ShouldBeCombinedFailureAsync(this ValueTask<Result> task, int expectedErrorCount, string? message = null)

    Asserts that the `ValueTask<Result>` is a combined failure with the expected inner error count.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedErrorCount: int
    The expected number of combined failures (inner errors).
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the root error with its inner errors.

  • methodShouldBeCombinedFailureAsync<T>
    public static Task<Error> ShouldBeCombinedFailureAsync<T>(this Task<Result<T>> task, int expectedErrorCount, string? message = null)

    Asserts that the `Task<Result<T>>` is a combined failure with the expected inner error count.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedErrorCount: int
    The expected number of combined failures (inner errors).
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the root error with its inner errors.

    Type parameters: T: The value type of the result.

  • methodShouldBeCombinedFailureAsync<T>
    public static ValueTask<Error> ShouldBeCombinedFailureAsync<T>(this ValueTask<Result<T>> task, int expectedErrorCount, string? message = null)

    Asserts that the `ValueTask<Result<T>>` is a combined failure with the expected inner error count.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedErrorCount: int
    The expected number of combined failures (inner errors).
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the root error with its inner errors.

    Type parameters: T: The value type of the result.

  • methodShouldBeFailure
    public static Error ShouldBeFailure(this in Result result, string? message = null)

    Asserts that the Result is a failure and returns its Error.

    result: this in Result
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure

  • methodShouldBeFailure<T>
    public static Error ShouldBeFailure<T>(this in Result<T> result, string? message = null)

    Asserts that the Result<T> is a failure and returns its Error.

    result: this in Result<T>
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure

  • methodShouldBeFailureAsync
    public static Task<Error> ShouldBeFailureAsync(this Task<Result> task, string? message = null)

    Asserts that the `Task<Result>` is a failure and returns its error.

    task: this Task<Result>
    The task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldBeFailureAsync
    public static ValueTask<Error> ShouldBeFailureAsync(this ValueTask<Result> task, string? message = null)

    Asserts that the `ValueTask<Result>` is a failure and returns its error.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldBeFailureAsync<T>
    public static Task<Error> ShouldBeFailureAsync<T>(this Task<Result<T>> task, string? message = null)

    Asserts that the `Task<Result<T>>` is a failure and returns its error.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldBeFailureAsync<T>
    public static ValueTask<Error> ShouldBeFailureAsync<T>(this ValueTask<Result<T>> task, string? message = null)

    Asserts that the `ValueTask<Result<T>>` is a failure and returns its error.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldBePermanent
    public static Error ShouldBePermanent(this in Result result)

    Asserts that the Result error is permanent (not retryable).

    result: this in Result
    The result to inspect.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its retryability is not `ErrorRetryability.Permanent`

  • methodShouldBePermanent<T>
    public static Error ShouldBePermanent<T>(this in Result<T> result)

    Asserts that the Result<T> error is permanent (not retryable).

    result: this in Result<T>
    The result to inspect.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its retryability is not `ErrorRetryability.Permanent`

  • methodShouldBePermanentAsync
    public static Task<Error> ShouldBePermanentAsync(this Task<Result> task)

    Asserts that `Task<Result>` error is permanent (not retryable).

    task: this Task<Result>
    The task returning the result to inspect.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldBePermanentAsync
    public static ValueTask<Error> ShouldBePermanentAsync(this ValueTask<Result> task)

    Asserts that `ValueTask<Result>` error is permanent (not retryable).

    task: this ValueTask<Result>
    The value task returning the result to inspect.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldBePermanentAsync<T>
    public static Task<Error> ShouldBePermanentAsync<T>(this Task<Result<T>> task)

    Asserts that `Task<Result<T>>` error is permanent (not retryable).

    task: this Task<Result<T>>
    The task returning the result to inspect.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldBePermanentAsync<T>
    public static ValueTask<Error> ShouldBePermanentAsync<T>(this ValueTask<Result<T>> task)

    Asserts that `ValueTask<Result<T>>` error is permanent (not retryable).

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldBeRetryable
    public static Error ShouldBeRetryable(this in Result result)

    Asserts that the Result error is retryable (Transient).

    result: this in Result
    The result to inspect.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its retryability is not `ErrorRetryability.Transient`

  • methodShouldBeRetryable<T>
    public static Error ShouldBeRetryable<T>(this in Result<T> result)

    Asserts that the Result<T> error is retryable (Transient).

    result: this in Result<T>
    The result to inspect.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its retryability is not `ErrorRetryability.Transient`

  • methodShouldBeRetryableAsync
    public static Task<Error> ShouldBeRetryableAsync(this Task<Result> task)

    Asserts that `Task<Result>` error is retryable (Transient).

    task: this Task<Result>
    The task returning the result to inspect.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldBeRetryableAsync
    public static ValueTask<Error> ShouldBeRetryableAsync(this ValueTask<Result> task)

    Asserts that `ValueTask<Result>` error is retryable (Transient).

    task: this ValueTask<Result>
    The value task returning the result to inspect.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldBeRetryableAsync<T>
    public static Task<Error> ShouldBeRetryableAsync<T>(this Task<Result<T>> task)

    Asserts that `Task<Result<T>>` error is retryable (Transient).

    task: this Task<Result<T>>
    The task returning the result to inspect.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldBeRetryableAsync<T>
    public static ValueTask<Error> ShouldBeRetryableAsync<T>(this ValueTask<Result<T>> task)

    Asserts that `ValueTask<Result<T>>` error is retryable (Transient).

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldBeSuccess
    public static Result ShouldBeSuccess(this in Result result, string? message = null)

    Asserts that the Result is successful.

    result: this in Result
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The original result for chaining.

    Exceptions: ResultAssertionException: The result is not a success

  • methodShouldBeSuccess<T>
    public static T ShouldBeSuccess<T>(this in Result<T> result, string? message = null)

    Asserts that the Result<T> is successful and returns its value.

    result: this in Result<T>
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The success value.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a success

  • methodShouldBeSuccessAsync
    public static Task<Result> ShouldBeSuccessAsync(this Task<Result> task, string? message = null)

    Asserts that the `Task<Result>` is successful.

    task: this Task<Result>
    The task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the original result.

  • methodShouldBeSuccessAsync
    public static ValueTask<Result> ShouldBeSuccessAsync(this ValueTask<Result> task, string? message = null)

    Asserts that the `ValueTask<Result>` is successful.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the original result.

  • methodShouldBeSuccessAsync<T>
    public static Task<T> ShouldBeSuccessAsync<T>(this Task<Result<T>> task, string? message = null)

    Asserts that the `Task<Result<T>>` is successful and returns the value.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the success value.

    Type parameters: T: The value type of the result.

  • methodShouldBeSuccessAsync<T>
    public static ValueTask<T> ShouldBeSuccessAsync<T>(this ValueTask<Result<T>> task, string? message = null)

    Asserts that the `ValueTask<Result<T>>` is successful and returns the value.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the success value.

    Type parameters: T: The value type of the result.

  • methodShouldBeUninitialized
    public static Result ShouldBeUninitialized(this in Result result, string? message = null)

    Asserts that the Result is in the uninitialized default state (i.e., `default(Result)` was never replaced by `Result.Success()` or `Result.Failure`).

    result: this in Result
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The original uninitialized result.

    Use this assertion to verify that code paths that should always initialize a Result do not accidentally return `default(Result)`. The uninitialized state is neither Success nor Failure — it is a third sentinel state that typically indicates a programming error. Exceptions: ResultAssertionException: The result is not in the uninitialized state

  • methodShouldBeUninitialized<T>
    public static Result<T> ShouldBeUninitialized<T>(this in Result<T> result, string? message = null)

    Asserts that the Result<T> is in the uninitialized default state.

    result: this in Result<T>
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The original uninitialized result.

    Use this assertion to verify that code paths that should always initialize a Result<T> do not accidentally return `default(Result<T>)`. Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not in the uninitialized state

  • methodShouldBeUninitializedAsync
    public static Task<Result> ShouldBeUninitializedAsync(this Task<Result> task, string? message = null)

    Asserts that the `Task<Result>` is in the uninitialized default state.

    task: this Task<Result>
    The task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the uninitialized result.

  • methodShouldBeUninitializedAsync
    public static ValueTask<Result> ShouldBeUninitializedAsync(this ValueTask<Result> task, string? message = null)

    Asserts that the `ValueTask<Result>` is in the uninitialized default state.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the uninitialized result.

  • methodShouldBeUninitializedAsync<T>
    public static Task<Result<T>> ShouldBeUninitializedAsync<T>(this Task<Result<T>> task, string? message = null)

    Asserts that the `Task<Result<T>>` is in the uninitialized default state.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the uninitialized result.

    Type parameters: T: The value type of the result.

  • methodShouldBeUninitializedAsync<T>
    public static ValueTask<Result<T>> ShouldBeUninitializedAsync<T>(this ValueTask<Result<T>> task, string? message = null)

    Asserts that the `ValueTask<Result<T>>` is in the uninitialized default state.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the uninitialized result.

    Type parameters: T: The value type of the result.

  • methodShouldContainInnerError
    public static Error ShouldContainInnerError(this in Result result, string errorCode)

    Asserts that the Result error has at least one inner error with the specified error code.

    result: this in Result
    The result to inspect.
    errorCode: string
    The error code to search for within the inner errors.

    Returns: The root error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or no inner error has the specified `errorCode`

  • methodShouldContainInnerError<T>
    public static Error ShouldContainInnerError<T>(this in Result<T> result, string errorCode)

    Asserts that the Result<T> error has at least one inner error with the specified error code.

    result: this in Result<T>
    The result to inspect.
    errorCode: string
    The error code to search for within the inner errors.

    Returns: The root error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or no inner error has the specified `errorCode`

  • methodShouldContainInnerErrorAsync
    public static Task<Error> ShouldContainInnerErrorAsync(this Task<Result> task, string errorCode)

    Asserts that `Task<Result>` has at least one inner error with the specified error code.

    task: this Task<Result>
    The task returning the result to inspect.
    errorCode: string
    The error code to search for within the inner errors.

    Returns: A task representing the asynchronous assertion. The task result contains the root error from the failed result.

  • methodShouldContainInnerErrorAsync
    public static ValueTask<Error> ShouldContainInnerErrorAsync(this ValueTask<Result> task, string errorCode)

    Asserts that `ValueTask<Result>` has at least one inner error with the specified error code.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    errorCode: string
    The error code to search for within the inner errors.

    Returns: A value task representing the asynchronous assertion. The task result contains the root error from the failed result.

  • methodShouldContainInnerErrorAsync<T>
    public static Task<Error> ShouldContainInnerErrorAsync<T>(this Task<Result<T>> task, string errorCode)

    Asserts that `Task<Result<T>>` has at least one inner error with the specified error code.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    errorCode: string
    The error code to search for within the inner errors.

    Returns: A task representing the asynchronous assertion. The task result contains the root error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldContainInnerErrorAsync<T>
    public static ValueTask<Error> ShouldContainInnerErrorAsync<T>(this ValueTask<Result<T>> task, string errorCode)

    Asserts that `ValueTask<Result<T>>` has at least one inner error with the specified error code.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    errorCode: string
    The error code to search for within the inner errors.

    Returns: A value task representing the asynchronous assertion. The task result contains the root error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveCorrelationId
    public static Error ShouldHaveCorrelationId(this in Result result, string expectedCorrelationId)

    Asserts that the Result error has the expected CorrelationId.

    result: this in Result
    The result to inspect.
    expectedCorrelationId: string
    The expected correlation ID string.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its correlation ID does not match `expectedCorrelationId`

  • methodShouldHaveCorrelationId<T>
    public static Error ShouldHaveCorrelationId<T>(this in Result<T> result, string expectedCorrelationId)

    Asserts that the Result<T> error has the expected CorrelationId.

    result: this in Result<T>
    The result to inspect.
    expectedCorrelationId: string
    The expected correlation ID string.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its correlation ID does not match `expectedCorrelationId`

  • methodShouldHaveCorrelationIdAsync
    public static Task<Error> ShouldHaveCorrelationIdAsync(this Task<Result> task, string expectedCorrelationId)

    Asserts that `Task<Result>` error has the expected correlation ID.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedCorrelationId: string
    The expected correlation ID string.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveCorrelationIdAsync
    public static ValueTask<Error> ShouldHaveCorrelationIdAsync(this ValueTask<Result> task, string expectedCorrelationId)

    Asserts that `ValueTask<Result>` error has the expected correlation ID.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedCorrelationId: string
    The expected correlation ID string.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveCorrelationIdAsync<T>
    public static Task<Error> ShouldHaveCorrelationIdAsync<T>(this Task<Result<T>> task, string expectedCorrelationId)

    Asserts that `Task<Result<T>>` error has the expected correlation ID.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedCorrelationId: string
    The expected correlation ID string.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveCorrelationIdAsync<T>
    public static ValueTask<Error> ShouldHaveCorrelationIdAsync<T>(this ValueTask<Result<T>> task, string expectedCorrelationId)

    Asserts that `ValueTask<Result<T>>` error has the expected correlation ID.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedCorrelationId: string
    The expected correlation ID string.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveDescription
    public static Error ShouldHaveDescription(this in Result result, string expectedDescription)

    Asserts that the Result error has the expected description.

    result: this in Result
    The result to inspect.
    expectedDescription: string
    The expected error description string.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its description does not match `expectedDescription`

  • methodShouldHaveDescription<T>
    public static Error ShouldHaveDescription<T>(this in Result<T> result, string expectedDescription)

    Asserts that the Result<T> error has the expected description.

    result: this in Result<T>
    The result to inspect.
    expectedDescription: string
    The expected error description string.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its description does not match `expectedDescription`

  • methodShouldHaveDescriptionAsync
    public static Task<Error> ShouldHaveDescriptionAsync(this Task<Result> task, string expectedDescription)

    Asserts that `Task<Result>` error has the expected description.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedDescription: string
    The expected error description string.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveDescriptionAsync
    public static ValueTask<Error> ShouldHaveDescriptionAsync(this ValueTask<Result> task, string expectedDescription)

    Asserts that `ValueTask<Result>` error has the expected description.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedDescription: string
    The expected error description string.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveDescriptionAsync<T>
    public static Task<Error> ShouldHaveDescriptionAsync<T>(this Task<Result<T>> task, string expectedDescription)

    Asserts that `Task<Result<T>>` error has the expected description.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedDescription: string
    The expected error description string.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveDescriptionAsync<T>
    public static ValueTask<Error> ShouldHaveDescriptionAsync<T>(this ValueTask<Result<T>> task, string expectedDescription)

    Asserts that `ValueTask<Result<T>>` error has the expected description.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedDescription: string
    The expected error description string.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveErrorCode
    public static Error ShouldHaveErrorCode(this in Result result, string expectedErrorCode)

    Asserts that the Result failed with a specific error code.

    result: this in Result
    The result to inspect.
    expectedErrorCode: string
    The expected error code string.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its error code does not match `expectedErrorCode`

  • methodShouldHaveErrorCode<T>
    public static Error ShouldHaveErrorCode<T>(this in Result<T> result, string expectedErrorCode)

    Asserts that the Result<T> failed with a specific error code.

    result: this in Result<T>
    The result to inspect.
    expectedErrorCode: string
    The expected error code string.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its error code does not match `expectedErrorCode`

  • methodShouldHaveErrorCodeAsync
    public static Task<Error> ShouldHaveErrorCodeAsync(this Task<Result> task, string expectedCode)

    Asserts that `Task<Result>` is a failure with the given error code.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedCode: string
    The expected error code string.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveErrorCodeAsync
    public static ValueTask<Error> ShouldHaveErrorCodeAsync(this ValueTask<Result> task, string expectedCode)

    Asserts that `ValueTask<Result>` is a failure with the given error code.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedCode: string
    The expected error code string.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveErrorCodeAsync<T>
    public static Task<Error> ShouldHaveErrorCodeAsync<T>(this Task<Result<T>> task, string expectedCode)

    Asserts that `Task<Result<T>>` is a failure with the given error code.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedCode: string
    The expected error code string.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveErrorCodeAsync<T>
    public static ValueTask<Error> ShouldHaveErrorCodeAsync<T>(this ValueTask<Result<T>> task, string expectedCode)

    Asserts that `ValueTask<Result<T>>` is a failure with the given error code.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedCode: string
    The expected error code string.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveErrorCount
    public static Error ShouldHaveErrorCount(this in Result result, int expectedCount)

    Asserts that the failure result's root error has exactly `expectedCount` inner errors (i.e., errors aggregated from a `Result.Combine` call or similar multi-error operation).

    result: this in Result
    The result to inspect.
    expectedCount: int
    The expected number of inner errors.

    Returns: The error from the failed result.

    This is a named alias for `ShouldHaveInnerErrors(in Result, int)` for scenarios where the intent is to verify the number of combined failures without examining each individual error.

    // Assert that 3 operations failed when combined:
    result.ShouldHaveErrorCount(3);

    Exceptions: ResultAssertionException: The result is not a failure or the inner error count does not match `expectedCount`

  • methodShouldHaveErrorCount
    public static Error ShouldHaveErrorCount(this in Result result, int expectedCount, string? message = null)

    Asserts that the Result is a failure and has the exact number of inner errors.

    result: this in Result
    The result to inspect.
    expectedCount: int
    The expected number of inner errors.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or the inner error count does not match `expectedCount`

  • methodShouldHaveErrorCount<T>
    public static Error ShouldHaveErrorCount<T>(this in Result<T> result, int expectedCount)

    Asserts that the Result<T> failure's root error has exactly `expectedCount` inner errors.

    result: this in Result<T>
    The result to inspect.
    expectedCount: int
    The expected number of inner errors.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the inner error count does not match `expectedCount`

  • methodShouldHaveErrorCount<T>
    public static Error ShouldHaveErrorCount<T>(this in Result<T> result, int expectedCount, string? message = null)

    Asserts that the Result<T> is a failure and has the exact number of inner errors.

    result: this in Result<T>
    The result to inspect.
    expectedCount: int
    The expected number of inner errors.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the inner error count does not match `expectedCount`

  • methodShouldHaveErrorMatching
    public static Error ShouldHaveErrorMatching(this in Result result, Func<Error, bool> predicate, string? message = null)

    Asserts that the Result is a failure and that its error satisfies the given predicate.

    result: this in Result
    The result to inspect.
    predicate: Func<Error, bool>
    A predicate the error must satisfy.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Use this when you need to verify a combination of error properties in a single assertion without breaking the fluent chain. Unlike multiple individual `ShouldHave*` assertions, enables expressing complex conditions in a single readable predicate. Example:

    result.ShouldHaveErrorMatching(e => e.Code == "Order.NotFound" && e.Severity == ErrorSeverity.Critical);
    result.ShouldHaveErrorMatching(e => e.HasMetadata && e.Metadata.ContainsKey("orderId"), "Expected orderId metadata");
  • methodShouldHaveErrorMatching<T>
    public static Error ShouldHaveErrorMatching<T>(this in Result<T> result, Func<Error, bool> predicate, string? message = null)

    Asserts that the Result<T> is a failure and that its error satisfies the given predicate.

    result: this in Result<T>
    The result to inspect.
    predicate: Func<Error, bool>
    A predicate the error must satisfy.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveErrorMatchingAsync
    public static Task<Error> ShouldHaveErrorMatchingAsync(this Task<Result> task, Func<Error, bool> predicate, string? message = null)

    Asserts that the `Task<Result>` is a failure and that its error satisfies the given predicate.

    task: this Task<Result>
    The task returning the result to inspect.
    predicate: Func<Error, bool>
    A predicate the error must satisfy.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveErrorMatchingAsync
    public static ValueTask<Error> ShouldHaveErrorMatchingAsync(this ValueTask<Result> task, Func<Error, bool> predicate, string? message = null)

    Asserts that the `ValueTask<Result>` is a failure and that its error satisfies the given predicate.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    predicate: Func<Error, bool>
    A predicate the error must satisfy.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveErrorMatchingAsync<T>
    public static Task<Error> ShouldHaveErrorMatchingAsync<T>(this Task<Result<T>> task, Func<Error, bool> predicate, string? message = null)

    Asserts that the `Task<Result<T>>` is a failure and that its error satisfies the given predicate.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    predicate: Func<Error, bool>
    A predicate the error must satisfy.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveErrorMatchingAsync<T>
    public static ValueTask<Error> ShouldHaveErrorMatchingAsync<T>(this ValueTask<Result<T>> task, Func<Error, bool> predicate, string? message = null)

    Asserts that the `ValueTask<Result<T>>` is a failure and that its error satisfies the given predicate.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    predicate: Func<Error, bool>
    A predicate the error must satisfy.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveErrorType
    public static Error ShouldHaveErrorType(this in Result result, ErrorType expectedType)

    Asserts that the Result failed with a specific ErrorType.

    result: this in Result
    The result to inspect.
    expectedType: ErrorType
    The expected error type.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its error type does not match `expectedType`

  • methodShouldHaveErrorType<T>
    public static Error ShouldHaveErrorType<T>(this in Result<T> result, ErrorType expectedType)

    Asserts that the Result<T> failed with a specific ErrorType.

    result: this in Result<T>
    The result to inspect.
    expectedType: ErrorType
    The expected error type.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its error type does not match `expectedType`

  • methodShouldHaveErrorTypeAsync
    public static Task<Error> ShouldHaveErrorTypeAsync(this Task<Result> task, ErrorType expectedType)

    Asserts that `Task<Result>` is a failure with the given error type.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedType: ErrorType
    The expected `ErrorType`.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveErrorTypeAsync
    public static ValueTask<Error> ShouldHaveErrorTypeAsync(this ValueTask<Result> task, ErrorType expectedType)

    Asserts that `ValueTask<Result>` is a failure with the given error type.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedType: ErrorType
    The expected `ErrorType`.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveErrorTypeAsync<T>
    public static Task<Error> ShouldHaveErrorTypeAsync<T>(this Task<Result<T>> task, ErrorType expectedType)

    Asserts that `Task<Result<T>>` is a failure with the given error type.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedType: ErrorType
    The expected `ErrorType`.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveErrorTypeAsync<T>
    public static ValueTask<Error> ShouldHaveErrorTypeAsync<T>(this ValueTask<Result<T>> task, ErrorType expectedType)

    Asserts that `ValueTask<Result<T>>` is a failure with the given error type.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedType: ErrorType
    The expected `ErrorType`.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveInnerErrorCount
    public static Error ShouldHaveInnerErrorCount(this in Result result, int expectedCount, string? message = null)

    Asserts that the Result failure's error has exactly `expectedCount` inner errors. Useful for verifying `Result.Combine(ReadOnlySpan<Result>)` produced the expected number of collected failures.

    result: this in Result
    The result to inspect.
    expectedCount: int
    The expected number of inner errors.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or the inner error count does not match `expectedCount`

  • methodShouldHaveInnerErrorCount<T>
    public static Error ShouldHaveInnerErrorCount<T>(this in Result<T> result, int expectedCount, string? message = null)

    Asserts that the Result<T> failure's error has exactly `expectedCount` inner errors.

    result: this in Result<T>
    The result to inspect.
    expectedCount: int
    The expected number of inner errors.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the inner error count does not match `expectedCount`

  • methodShouldHaveInnerErrorCountAsync
    public static Task<Error> ShouldHaveInnerErrorCountAsync(this Task<Result> task, int expectedCount, string? message = null)

    Asserts that the `Task<Result>` failure's error has exactly `expectedCount` inner errors.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedCount: int
    The expected number of inner errors.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveInnerErrorCountAsync
    public static ValueTask<Error> ShouldHaveInnerErrorCountAsync(this ValueTask<Result> task, int expectedCount, string? message = null)

    Asserts that the `ValueTask<Result>` failure's error has exactly `expectedCount` inner errors.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedCount: int
    The expected number of inner errors.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveInnerErrorCountAsync<T>
    public static Task<Error> ShouldHaveInnerErrorCountAsync<T>(this Task<Result<T>> task, int expectedCount, string? message = null)

    Asserts that the `Task<Result<T>>` failure's error has exactly `expectedCount` inner errors.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedCount: int
    The expected number of inner errors.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveInnerErrorCountAsync<T>
    public static ValueTask<Error> ShouldHaveInnerErrorCountAsync<T>(this ValueTask<Result<T>> task, int expectedCount, string? message = null)

    Asserts that the `ValueTask<Result<T>>` failure's error has exactly `expectedCount` inner errors.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedCount: int
    The expected number of inner errors.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveInnerErrors
    public static Error ShouldHaveInnerErrors(this in Result result, int expectedCount)

    Asserts that the Result failed with inner errors of expected count.

    result: this in Result
    The result to inspect.
    expectedCount: int
    The expected number of inner errors.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or the inner error count does not match `expectedCount`

  • methodShouldHaveInnerErrors<T>
    public static Error ShouldHaveInnerErrors<T>(this in Result<T> result, int expectedCount)

    Asserts that the Result<T> failed with inner errors of expected count.

    result: this in Result<T>
    The result to inspect.
    expectedCount: int
    The expected number of inner errors.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the inner error count does not match `expectedCount`

  • methodShouldHaveInnerErrorsAsync
    public static Task<Error> ShouldHaveInnerErrorsAsync(this Task<Result> task, int expectedCount)

    Asserts that `Task<Result>` has inner errors of expected count.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedCount: int
    The expected number of inner errors.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveInnerErrorsAsync
    public static ValueTask<Error> ShouldHaveInnerErrorsAsync(this ValueTask<Result> task, int expectedCount)

    Asserts that `ValueTask<Result>` has inner errors of expected count.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedCount: int
    The expected number of inner errors.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveInnerErrorsAsync<T>
    public static Task<Error> ShouldHaveInnerErrorsAsync<T>(this Task<Result<T>> task, int expectedCount)

    Asserts that `Task<Result<T>>` has inner errors of expected count.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedCount: int
    The expected number of inner errors.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveInnerErrorsAsync<T>
    public static ValueTask<Error> ShouldHaveInnerErrorsAsync<T>(this ValueTask<Result<T>> task, int expectedCount)

    Asserts that `ValueTask<Result<T>>` has inner errors of expected count.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedCount: int
    The expected number of inner errors.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveInnerErrorsMatching
    public static Error ShouldHaveInnerErrorsMatching(this in Result result, Func<System.Collections.Immutable.ImmutableArray<Error>, bool> predicate, string? message = null)

    Asserts that the Result is a failure and its inner errors satisfy the given predicate.

    result: this in Result
    The result to inspect.
    predicate: Func<System.Collections.Immutable.ImmutableArray<Error>, bool>
    A predicate that the inner errors collection must satisfy.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or the inner errors do not satisfy `predicate`

  • methodShouldHaveInnerErrorsMatching<T>
    public static Error ShouldHaveInnerErrorsMatching<T>(this in Result<T> result, Func<System.Collections.Immutable.ImmutableArray<Error>, bool> predicate, string? message = null)

    Asserts that the Result<T> is a failure and its inner errors satisfy the given predicate.

    result: this in Result<T>
    The result to inspect.
    predicate: Func<System.Collections.Immutable.ImmutableArray<Error>, bool>
    A predicate that the inner errors collection must satisfy.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the inner errors do not satisfy `predicate`

  • methodShouldHaveMetadata
    public static Error ShouldHaveMetadata(this in Result result, string key, object expectedValue)

    Asserts that the Result failed with a specific metadata key and value.

    result: this in Result
    The result to inspect.
    key: string
    The metadata key to look up.
    expectedValue: object
    The expected value corresponding to `key`.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or the metadata key/value does not match

  • methodShouldHaveMetadata<T>
    public static Error ShouldHaveMetadata<T>(this in Result<T> result, string key, object expectedValue)

    Asserts that the Result<T> failed with a specific metadata key and value.

    result: this in Result<T>
    The result to inspect.
    key: string
    The metadata key to look up.
    expectedValue: object
    The expected value corresponding to `key`.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the metadata key/value does not match

  • methodShouldHaveMetadataAsync
    public static Task<Error> ShouldHaveMetadataAsync(this Task<Result> task, string key, object expectedValue)

    Asserts that `Task<Result>` is a failure and the error has the given metadata key and value.

    task: this Task<Result>
    The task returning the result to inspect.
    key: string
    The metadata key to look up.
    expectedValue: object
    The expected metadata value.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveMetadataAsync
    public static ValueTask<Error> ShouldHaveMetadataAsync(this ValueTask<Result> task, string key, object expectedValue)

    Asserts that `ValueTask<Result>` is a failure and the error has the given metadata key and value.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    key: string
    The metadata key to look up.
    expectedValue: object
    The expected metadata value.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveMetadataAsync<T>
    public static Task<Error> ShouldHaveMetadataAsync<T>(this Task<Result<T>> task, string key, object expectedValue)

    Asserts that `Task<Result<T>>` is a failure and the error has the given metadata key and value.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    key: string
    The metadata key to look up.
    expectedValue: object
    The expected metadata value.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveMetadataAsync<T>
    public static ValueTask<Error> ShouldHaveMetadataAsync<T>(this ValueTask<Result<T>> task, string key, object expectedValue)

    Asserts that `ValueTask<Result<T>>` is a failure and the error has the given metadata key and value.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    key: string
    The metadata key to look up.
    expectedValue: object
    The expected metadata value.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveMetadataKey
    public static Error ShouldHaveMetadataKey(this in Result result, string key)

    Asserts that the Result error contains a metadata entry with the specified key, regardless of the value. Use `ShouldHaveMetadata(in Result, string, object)` to also assert the value.

    result: this in Result
    The result to inspect.
    key: string
    The metadata key to look up.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or the key is not present in the error metadata

  • methodShouldHaveMetadataKey<T>
    public static Error ShouldHaveMetadataKey<T>(this in Result<T> result, string key)

    Asserts that the Result<T> error contains a metadata entry with the specified key, regardless of the value. Use `ShouldHaveMetadata<T>(in Result<T>, string, object)` to also assert the value.

    result: this in Result<T>
    The result to inspect.
    key: string
    The metadata key to look up.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the key is not present in the error metadata

  • methodShouldHaveMetadataValue<T, TValue>
    public static Error ShouldHaveMetadataValue<T, TValue>(this in Result<T> result, string key, TValue expectedValue, string? message = null)

    Asserts that the Result<T> is a failure and that its error metadata contains `key` with a typed value equal to `expectedValue`.

    result: this in Result<T>
    The result to inspect.
    key: string
    The metadata key to look up.
    expectedValue: TValue
    The expected value after casting to `TValue`.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result.; TValue: The expected type of the metadata value. Exceptions: ResultAssertionException: The result is not a failure or the metadata key/value does not match

  • methodShouldHaveMetadataValue<TValue>
    public static Error ShouldHaveMetadataValue<TValue>(this in Result result, string key, TValue expectedValue, string? message = null)

    Asserts that the Result is a failure and that its error metadata contains `key` with a value that can be cast to `TValue` and that equals `expectedValue`.

    result: this in Result
    The result to inspect.
    key: string
    The metadata key to look up.
    expectedValue: TValue
    The expected value after casting to `TValue`.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Unlike `ShouldHaveMetadata(in Result, string, object)` which uses `object` equality, performs a typed cast first. This is necessary for value types (e.g., `long`, `int`) where boxing differences could cause `Equals` to return `false` even with identical values. Type parameters: TValue: The expected type of the metadata value. Example:

    result.ShouldHaveMetadataValue<long>("orderId", 42L);
    result.ShouldHaveMetadataValue<string>("region", "us-east-1");
  • methodShouldHaveNoInnerErrors
    public static Error ShouldHaveNoInnerErrors(this in Result result, string? message = null)

    Asserts that the Result failure has no inner errors.

    result: this in Result
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    This is the complement of `ShouldHaveInnerErrors(in Result, int)`. Use it when you expect a failure with a single root error and no nested errors. Exceptions: ResultAssertionException: The result is not a failure or it has one or more inner errors

  • methodShouldHaveNoInnerErrors<T>
    public static Error ShouldHaveNoInnerErrors<T>(this in Result<T> result, string? message = null)

    Asserts that the Result<T> failure has no inner errors.

    result: this in Result<T>
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    This is the complement of `ShouldHaveInnerErrors<T>(in Result<T>, int)`. Use it when you expect a failure with a single root error and no nested errors. Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or it has one or more inner errors

  • methodShouldHaveSeverity
    public static Error ShouldHaveSeverity(this in Result result, ErrorSeverity expectedSeverity)

    Asserts that the Result failed with a specific ErrorSeverity.

    result: this in Result
    The result to inspect.
    expectedSeverity: ErrorSeverity
    The expected error severity.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its severity does not match `expectedSeverity`

  • methodShouldHaveSeverity<T>
    public static Error ShouldHaveSeverity<T>(this in Result<T> result, ErrorSeverity expectedSeverity)

    Asserts that the Result<T> failed with a specific ErrorSeverity.

    result: this in Result<T>
    The result to inspect.
    expectedSeverity: ErrorSeverity
    The expected error severity.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its severity does not match `expectedSeverity`

  • methodShouldHaveSeverityAsync
    public static Task<Error> ShouldHaveSeverityAsync(this Task<Result> task, ErrorSeverity expectedSeverity)

    Asserts that `Task<Result>` is a failure with the given severity.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedSeverity: ErrorSeverity
    The expected `ErrorSeverity`.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveSeverityAsync
    public static ValueTask<Error> ShouldHaveSeverityAsync(this ValueTask<Result> task, ErrorSeverity expectedSeverity)

    Asserts that `ValueTask<Result>` is a failure with the given severity.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedSeverity: ErrorSeverity
    The expected `ErrorSeverity`.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveSeverityAsync<T>
    public static Task<Error> ShouldHaveSeverityAsync<T>(this Task<Result<T>> task, ErrorSeverity expectedSeverity)

    Asserts that `Task<Result<T>>` is a failure with the given severity.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedSeverity: ErrorSeverity
    The expected `ErrorSeverity`.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveSeverityAsync<T>
    public static ValueTask<Error> ShouldHaveSeverityAsync<T>(this ValueTask<Result<T>> task, ErrorSeverity expectedSeverity)

    Asserts that `ValueTask<Result<T>>` is a failure with the given severity.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedSeverity: ErrorSeverity
    The expected `ErrorSeverity`.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveTraceId
    public static Error ShouldHaveTraceId(this in Result result, string expectedTraceId)

    Asserts that the Result error has the expected OpenTelemetry TraceId.

    result: this in Result
    The result to inspect.
    expectedTraceId: string
    The expected trace ID string.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its trace ID does not match `expectedTraceId`

  • methodShouldHaveTraceId<T>
    public static Error ShouldHaveTraceId<T>(this in Result<T> result, string expectedTraceId)

    Asserts that the Result<T> error has the expected OpenTelemetry TraceId.

    result: this in Result<T>
    The result to inspect.
    expectedTraceId: string
    The expected trace ID string.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its trace ID does not match `expectedTraceId`

  • methodShouldHaveTraceIdAsync
    public static Task<Error> ShouldHaveTraceIdAsync(this Task<Result> task, string expectedTraceId)

    Asserts that `Task<Result>` error has the expected trace ID.

    task: this Task<Result>
    The task returning the result to inspect.
    expectedTraceId: string
    The expected trace ID string.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveTraceIdAsync
    public static ValueTask<Error> ShouldHaveTraceIdAsync(this ValueTask<Result> task, string expectedTraceId)

    Asserts that `ValueTask<Result>` error has the expected trace ID.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    expectedTraceId: string
    The expected trace ID string.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldHaveTraceIdAsync<T>
    public static Task<Error> ShouldHaveTraceIdAsync<T>(this Task<Result<T>> task, string expectedTraceId)

    Asserts that `Task<Result<T>>` error has the expected trace ID.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedTraceId: string
    The expected trace ID string.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveTraceIdAsync<T>
    public static ValueTask<Error> ShouldHaveTraceIdAsync<T>(this ValueTask<Result<T>> task, string expectedTraceId)

    Asserts that `ValueTask<Result<T>>` error has the expected trace ID.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedTraceId: string
    The expected trace ID string.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldHaveValue<T>
    public static T ShouldHaveValue<T>(this in Result<T> result, Func<T, bool> predicate, string? message = null)

    Asserts that the Result<T> is successful and that its value satisfies the given predicate.

    result: this in Result<T>
    The result to inspect.
    predicate: Func<T, bool>
    A predicate the value must satisfy.
    message: string?
    Optional custom failure message.

    Returns: The value of the successful result.

    Type parameters: T: The value type of the result. Example:

    result.ShouldHaveValue(order => order.Total > 0);
    result.ShouldHaveValue(list => list.Count == 3, "Expected 3 items in the list.");
  • methodShouldHaveValue<T>
    public static T ShouldHaveValue<T>(this in Result<T> result, T expectedValue, string? message = null)

    Asserts that the Result<T> is successful and has the expected value.

    result: this in Result<T>
    The result to inspect.
    expectedValue: T
    The expected success value.
    message: string?
    Optional custom failure message.

    Returns: The success value.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a success or the value does not match `expectedValue`

  • methodShouldHaveValueAsync<T>
    public static Task<T> ShouldHaveValueAsync<T>(this Task<Result<T>> task, T expectedValue, string? message = null)

    Asserts that `Task<Result<T>>` is successful and has the expected value.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    expectedValue: T
    The expected success value.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the success value.

    Type parameters: T: The value type of the result.

  • methodShouldHaveValueAsync<T>
    public static ValueTask<T> ShouldHaveValueAsync<T>(this ValueTask<Result<T>> task, T expectedValue, string? message = null)

    Asserts that `ValueTask<Result<T>>` is successful and has the expected value.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    expectedValue: T
    The expected success value.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the success value.

    Type parameters: T: The value type of the result.

  • methodShouldNotHaveInnerErrors
    public static Error ShouldNotHaveInnerErrors(this in Result result, string? message = null)

    Asserts that the Result failure's error has no inner errors. This is the inverse of `ShouldHaveInnerErrors(in Result, int)`.

    result: this in Result
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or its error has one or more inner errors

  • methodShouldNotHaveInnerErrors<T>
    public static Error ShouldNotHaveInnerErrors<T>(this in Result<T> result, string? message = null)

    Asserts that the Result<T> failure's error has no inner errors.

    result: this in Result<T>
    The result to inspect.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or its error has one or more inner errors

  • methodShouldNotHaveInnerErrorsAsync
    public static Task<Error> ShouldNotHaveInnerErrorsAsync(this Task<Result> task, string? message = null)

    Asserts that the `Task<Result>` failure's error has no inner errors.

    task: this Task<Result>
    The task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldNotHaveInnerErrorsAsync
    public static ValueTask<Error> ShouldNotHaveInnerErrorsAsync(this ValueTask<Result> task, string? message = null)

    Asserts that the `ValueTask<Result>` failure's error has no inner errors.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldNotHaveInnerErrorsAsync<T>
    public static Task<Error> ShouldNotHaveInnerErrorsAsync<T>(this Task<Result<T>> task, string? message = null)

    Asserts that the `Task<Result<T>>` failure's error has no inner errors.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldNotHaveInnerErrorsAsync<T>
    public static ValueTask<Error> ShouldNotHaveInnerErrorsAsync<T>(this ValueTask<Result<T>> task, string? message = null)

    Asserts that the `ValueTask<Result<T>>` failure's error has no inner errors.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    message: string?
    Optional custom failure message.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldNotHaveMetadata
    public static Error ShouldNotHaveMetadata(this in Result result, string key)

    Asserts that the Result error does not contain a metadata entry with the specified key.

    result: this in Result
    The result to inspect.
    key: string
    The metadata key that must be absent.

    Returns: The error from the failed result.

    Exceptions: ResultAssertionException: The result is not a failure or the key is present in the error metadata

  • methodShouldNotHaveMetadata<T>
    public static Error ShouldNotHaveMetadata<T>(this in Result<T> result, string key)

    Asserts that the Result<T> error does not contain a metadata entry with the specified key.

    result: this in Result<T>
    The result to inspect.
    key: string
    The metadata key that must be absent.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the key is present in the error metadata

  • methodShouldSatisfy
    public static Result ShouldSatisfy(this in Result result, Action<Result> assertion, string? message = null)

    Asserts that the non-generic Result is successful and executes a custom assertion action.

    result: this in Result
    The result to assert on.
    assertion: Action<Result>
    An action that performs custom assertions on the result. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not successful.

    Returns: The result for further assertions.

    Example:

    result.ShouldSatisfy(r =>
    {
        Assert.True(r.IsSuccess);
    });
  • methodShouldSatisfy<T>
    public static T ShouldSatisfy<T>(this in Result<T> result, Action<T> assertion, string? message = null)

    Asserts that the Result<T> is successful and that its value satisfies the specified assertion action.

    result: this in Result<T>
    The result to assert on.
    assertion: Action<T>
    An action that performs custom assertions on the value. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not successful.

    Returns: The value for further assertions.

    Type parameters: T: The result value type. Example:

    result.ShouldSatisfy<OrderDto>(order =>
    {
        Assert.Equal("ORD-001", order.OrderId);
        Assert.True(order.Items.Count > 0);
    });
  • methodShouldSatisfyAsync
    public static Task<Result> ShouldSatisfyAsync(this Task<Result> task, Action<Result> assertion, string? message = null)

    Asserts that the `Task<Result>` is successful and executes a custom assertion action.

    task: this Task<Result>
    The task returning the result to inspect.
    assertion: Action<Result>
    An action that performs custom assertions on the result. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not successful.

    Returns: A task representing the asynchronous assertion. The task result contains the original result.

  • methodShouldSatisfyAsync
    public static ValueTask<Result> ShouldSatisfyAsync(this ValueTask<Result> task, Action<Result> assertion, string? message = null)

    Asserts that the `ValueTask<Result>` is successful and executes a custom assertion action.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    assertion: Action<Result>
    An action that performs custom assertions on the result. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not successful.

    Returns: A value task representing the asynchronous assertion. The task result contains the original result.

  • methodShouldSatisfyAsync<T>
    public static Task<T> ShouldSatisfyAsync<T>(this Task<Result<T>> task, Action<T> assertion, string? message = null)

    Asserts that the `Task<Result<T>>` is successful and that its value satisfies the specified assertion action.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    assertion: Action<T>
    An action that performs custom assertions on the value. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not successful.

    Returns: A task representing the asynchronous assertion. The task result contains the success value.

    Type parameters: T: The result value type.

  • methodShouldSatisfyAsync<T>
    public static ValueTask<T> ShouldSatisfyAsync<T>(this ValueTask<Result<T>> task, Action<T> assertion, string? message = null)

    Asserts that the `ValueTask<Result<T>>` is successful and that its value satisfies the specified assertion action.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    assertion: Action<T>
    An action that performs custom assertions on the value. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not successful.

    Returns: A value task representing the asynchronous assertion. The task result contains the success value.

    Type parameters: T: The result value type.

  • methodShouldSatisfyError
    public static Error ShouldSatisfyError(this in Result result, Action<Error> assertion, string? message = null)

    Asserts that the non-generic Result is a failure and executes a custom assertion action on the error.

    result: this in Result
    The result to assert on.
    assertion: Action<Error>
    An action that performs custom assertions on the error. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not a failure.

    Returns: The error for further chained assertions.

    Example:

    result.ShouldSatisfyError(error =>
    {
        Assert.Equal("NOT_FOUND", error.Code);
        Assert.True(error.HasMetadata);
    });
  • methodShouldSatisfyError<T>
    public static Error ShouldSatisfyError<T>(this in Result<T> result, Action<Error> assertion, string? message = null)

    Asserts that the Result<T> is a failure and executes a custom assertion action on the error.

    result: this in Result<T>
    The result to assert on.
    assertion: Action<Error>
    An action that performs custom assertions on the error. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not a failure.

    Returns: The error for further chained assertions.

    Type parameters: T: The result value type.

  • methodShouldSatisfyErrorAsync
    public static Task<Error> ShouldSatisfyErrorAsync(this Task<Result> task, Action<Error> assertion, string? message = null)

    Asserts that `Task<Result>` is a failure and the error satisfies the assertion.

    task: this Task<Result>
    The task returning the result to inspect.
    assertion: Action<Error>
    An action that performs custom assertions on the error. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not a failure.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldSatisfyErrorAsync
    public static ValueTask<Error> ShouldSatisfyErrorAsync(this ValueTask<Result> task, Action<Error> assertion, string? message = null)

    Asserts that `ValueTask<Result>` is a failure and the error satisfies the assertion.

    task: this ValueTask<Result>
    The value task returning the result to inspect.
    assertion: Action<Error>
    An action that performs custom assertions on the error. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not a failure.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

  • methodShouldSatisfyErrorAsync<T>
    public static Task<Error> ShouldSatisfyErrorAsync<T>(this Task<Result<T>> task, Action<Error> assertion, string? message = null)

    Asserts that `Task<Result<T>>` is a failure and the error satisfies the assertion.

    task: this Task<Result<T>>
    The task returning the result to inspect.
    assertion: Action<Error>
    An action that performs custom assertions on the error. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not a failure.

    Returns: A task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldSatisfyErrorAsync<T>
    public static ValueTask<Error> ShouldSatisfyErrorAsync<T>(this ValueTask<Result<T>> task, Action<Error> assertion, string? message = null)

    Asserts that `ValueTask<Result<T>>` is a failure and the error satisfies the assertion.

    task: this ValueTask<Result<T>>
    The value task returning the result to inspect.
    assertion: Action<Error>
    An action that performs custom assertions on the error. Throw any exception to indicate failure.
    message: string?
    Optional failure message if the result is not a failure.

    Returns: A value task representing the asynchronous assertion. The task result contains the error from the failed result.

    Type parameters: T: The value type of the result.

  • methodShouldStrictlyEqual
    public static Error ShouldStrictlyEqual(this in Result result, Error expected, string? message = null)

    Asserts that the Result failure's error is strictly equal to `expected` using `Error.StrictEquals`, which compares ALL fields including `Error.TraceId`, `Error.CorrelationId`, `Error.InnerErrors`, and `Error.Metadata`.

    result: this in Result
    The result to inspect.
    expected: Error
    The expected error to compare against using full field equality.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Use this instead of `ShouldHaveErrorCode` when you need to verify that all properties of an error match exactly — for example in tests that construct errors with specific trace IDs or metadata and need to verify the complete enrichment pipeline. For ordinary equality (Code, Description, Type, Severity, Retryability), use `ShouldHaveErrorCode` or the specialized `ShouldHave*` methods. To compare shallow equality across all five semantic fields, use `Error.Equals(Error?)` directly in a `ShouldSatisfyError` callback. Exceptions: ResultAssertionException: The result is not a failure or the error does not strictly equal `expected`

  • methodShouldStrictlyEqual<T>
    public static Error ShouldStrictlyEqual<T>(this in Result<T> result, Error expected, string? message = null)

    Asserts that the Result<T> failure's error is strictly equal to `expected` using `Error.StrictEquals`.

    result: this in Result<T>
    The result to inspect.
    expected: Error
    The expected error to compare against using full field equality.
    message: string?
    Optional custom failure message.

    Returns: The error from the failed result.

    Type parameters: T: The value type of the result. Exceptions: ResultAssertionException: The result is not a failure or the error does not strictly equal `expected`

EricksonLopez.Result.Testing.NUnit#

2
class

ResultAssertionNUnitException

Assembly: EricksonLopez.Result.Testing.NUnit
public sealed class ResultAssertionNUnitException : AssertionException
Inherits: AssertionException

Represents an exception thrown when a Result assertion fails, using NUnit's `AssertionException` as the base class so that failures appear as Failed in NUnit's test output — producing clean assertion messages.

Members (3)

  • constructorResultAssertionNUnitException
    public ResultAssertionNUnitException()

    Initializes a new instance of the `ResultAssertionNUnitException` class with a default message.

  • constructorResultAssertionNUnitException
    public ResultAssertionNUnitException(ResultAssertionException inner)

    Initializes a new instance of the `ResultAssertionNUnitException` class from an existing `ResultAssertionException`, preserving the original message.

    inner: ResultAssertionException
    The framework-agnostic assertion exception to wrap.
  • constructorResultAssertionNUnitException
    public ResultAssertionNUnitException(string message)

    Initializes a new instance of the `ResultAssertionNUnitException` class with a specified error message.

    message: string
    The error message that explains the assertion failure.
class

ResultNUnitAssertionConfig

Assembly: EricksonLopez.Result.Testing.NUnit
public static class ResultNUnitAssertionConfig

Provides configuration entry points for integrating `ResultAssertions` with NUnit.

Remarks:

By default, assertion failures thrown by `EricksonLopez.Result.Testing` derive from `Exception` and appear as Errors in NUnit output. Calling `UseNUnitExceptions` redirects exception creation to `ResultAssertionNUnitException`, which derives from `AssertionException` and displays as a clean Failed with only the assertion message.

Members (1)

  • methodUseNUnitExceptions
    public static void UseNUnitExceptions()

    Configures `ResultAssertions` to throw `ResultAssertionNUnitException` instead of the default `ResultAssertionException`. Safe to call multiple times.

EricksonLopez.Result.Testing.XUnit#

2
class

ResultAssertionXUnitException

Assembly: EricksonLopez.Result.Testing.XUnit
public sealed class ResultAssertionXUnitException : XunitException
Inherits: XunitException

Represents an exception thrown when a Result assertion fails, using xUnit's `XunitException` as the base class so that failures appear as Failure (not Error) in xUnit's test output — producing clean assertion messages without unnecessary stack trace noise.

Remarks:

xUnit v2 and v3 differentiate between two kinds of test-ending exceptions: - Failures: Exceptions that derive from `XunitException`. These display with only the assertion message — no stack trace from the assertion library internals. This is the expected behavior for assertion failures (e.g., from FluentAssertions, Shouldly). - Errors: Any other exception. These display with the full stack trace, making it harder to see what went wrong in the test. The base `Testing.ResultAssertionException` inherits from `Exception` and therefore shows as an Error in xUnit. Register this exception type in your xUnit test project by calling `ResultXUnitAssertionConfig.UseXUnitExceptions()` in your test assembly setup, or by using the `EricksonLopez.Result.Testing.XUnit` package and directly throwing this exception in custom assertion helpers. Framework independence: Kept in a separate package so that `EricksonLopez.Result.Testing` remains framework-agnostic (no xUnit dependency). NUnit and MSTest users should use `EricksonLopez.Result.Testing` directly.

Members (3)

  • constructorResultAssertionXUnitException
    public ResultAssertionXUnitException()

    Initializes a new instance of the `ResultAssertionXUnitException` class with a default message.

  • constructorResultAssertionXUnitException
    public ResultAssertionXUnitException(ResultAssertionException inner)

    Initializes a new instance of the `ResultAssertionXUnitException` class from an existing `ResultAssertionException`, preserving the original message.

    inner: ResultAssertionException
    The framework-agnostic assertion exception to wrap.
  • constructorResultAssertionXUnitException
    public ResultAssertionXUnitException(string message)

    Initializes a new instance of the `ResultAssertionXUnitException` class with a specified error message.

    message: string
    The error message that explains the assertion failure.
class

ResultXUnitAssertionConfig

Assembly: EricksonLopez.Result.Testing.XUnit
public static class ResultXUnitAssertionConfig

Provides configuration entry points for integrating `ResultAssertions` with xUnit v2 and v3.

Remarks:

By default, assertion failures thrown by `EricksonLopez.Result.Testing` derive from `Exception` and appear as Errors in xUnit output. Calling `UseXUnitExceptions` redirects exception creation to `ResultAssertionXUnitException`, which derives from `XunitException` and displays as a clean Failure with only the assertion message. Usage — call once during test setup, typically via a module initializer:

internal static class TestAssemblySetup
{
    [System.Runtime.CompilerServices.ModuleInitializer]
    internal static void Initialize() => ResultXUnitAssertionConfig.UseXUnitExceptions();
}

Members (1)

  • methodUseXUnitExceptions
    public static void UseXUnitExceptions()

    Configures `ResultAssertions` to throw `ResultAssertionXUnitException` instead of the default `ResultAssertionException`. Safe to call multiple times.

    Called automatically via `AutoConfigure` when the assembly loads. You only need to call this explicitly if you have called `Reset` and want to re-enable xUnit exception mode. Thread safety: Uses `Interlocked.CompareExchange(ref int, int, int)` to atomically check-and-set the configured flag, eliminating the TOCTOU race condition that would exist with a plain read-then-write pattern.

Search EricksonLopez.* Ecosystem

Type a library name, NuGet package ID, .NET type, or architectural concept to search across the portal.