Class Result<TValue>

Namespace
REslava.Result
Assembly
REslava.Result.dll

Represents the result of an operation with a value of type TValue. Immutable by design - all operations return new instances.

public class Result<TValue> : Result, IResultBase<TValue>, IResultBase

Type Parameters

TValue
Inheritance
Result<TValue>
Implements
IResultBase<TValue>
Derived
Inherited Members
Extension Methods

Constructors

Result()

Initializes a new instance of the Result<TValue> class with a default value. This constructor is protected and used internally for creating failed results.

protected Result()

Properties

Value

Gets the value if the result is successful.

public TValue? Value { get; }

Property Value

TValue

Examples

// Safe usage:
if (result.IsSuccess)
{
    var value = result.Value;  // Won't throw
}

// Or use Match:
var output = result.Match(
    onSuccess: value => DoSomething(value),
    onFailure: errors => HandleErrors(errors)
);

Exceptions

InvalidOperationException

Thrown when the result is failed. Use IsSuccess to check first, or use GetValueOr() for a safe alternative.

Methods

BindAsync<TOut>(Func<TValue, Task<Result<TOut>>>, CancellationToken)

Asynchronously chains another operation that returns a Result, allowing for sequential operations. Preserves success reasons from the original result in all cases. Also known as FlatMap or SelectMany.

public Task<Result<TOut>> BindAsync<TOut>(Func<TValue, Task<Result<TOut>>> binder, CancellationToken cancellationToken = default)

Parameters

binder Func<TValue, Task<Result<TOut>>>

The async function that returns a new Result.

cancellationToken CancellationToken

Optional cancellation token.

Returns

Task<Result<TOut>>

The result of the binder function with accumulated success reasons, or a failed result.

Type Parameters

TOut

The type of the output value.

Bind<TOut>(Func<TValue, Result<TOut>>)

Chains another operation that returns a Result, allowing for sequential operations. Preserves success reasons from the original result in all cases. Also known as FlatMap or SelectMany.

public Result<TOut> Bind<TOut>(Func<TValue, Result<TOut>> binder)

Parameters

binder Func<TValue, Result<TOut>>

The function that returns a new Result.

Returns

Result<TOut>

The result of the binder function with accumulated success reasons, or a failed result.

Type Parameters

TOut

The type of the output value.

CatchAsync<TException>(Func<TException, Task<IError>>, CancellationToken)

Asynchronously converts a typed exception inside a failed result to a different error.

public Task<Result<TValue>> CatchAsync<TException>(Func<TException, Task<IError>> handler, CancellationToken cancellationToken = default) where TException : Exception

Parameters

handler Func<TException, Task<IError>>

Async function that maps the caught exception to a replacement IError.

cancellationToken CancellationToken

Optional cancellation token.

Returns

Task<Result<TValue>>

The original result if successful or no matching exception error is found; otherwise a new failed result with the exception error replaced.

Type Parameters

TException

The exception type to handle. Subclasses are matched.

Catch<TException>(Func<TException, IError>)

Converts a typed exception inside a failed result to a different error. If the result contains an ExceptionError wrapping a TException, it is replaced with the error returned by handler. All other errors and success reasons are preserved. If the result is successful, or no matching exception error exists, the result is returned unchanged.

public Result<TValue> Catch<TException>(Func<TException, IError> handler) where TException : Exception

Parameters

handler Func<TException, IError>

Maps the caught exception to a replacement IError.

Returns

Result<TValue>

The original result if successful or no matching exception error is found; otherwise a new failed result with the exception error replaced.

Type Parameters

TException

The exception type to handle. Subclasses are matched.

Examples

var result = await Result.TryAsync(() => httpClient.GetUserAsync(id))
    .Catch<HttpRequestException>(ex => new NotFoundError("User", id));

Combine(params Result<TValue>[])

Combines results with params syntax.

public static Result<IEnumerable<TValue>> Combine(params Result<TValue>[] results)

Parameters

results Result<TValue>[]

Returns

Result<IEnumerable<TValue>>

Combine(IEnumerable<Result<TValue>>)

Combines multiple Result<T> - ALL must succeed. Returns Result<IEnumerable<T>> with all values if all succeeded.

public static Result<IEnumerable<TValue>> Combine(IEnumerable<Result<TValue>> results)

Parameters

results IEnumerable<Result<TValue>>

Returns

Result<IEnumerable<TValue>>

Examples

var users = Result<User>.Combine(
    GetUser(id1),
    GetUser(id2),
    GetUser(id3)
);
// users: Result<IEnumerable<User>>

CombineParallelAsync(IEnumerable<Task<Result<TValue>>>)

Combines results from parallel async operations.

public static Task<Result<IEnumerable<TValue>>> CombineParallelAsync(IEnumerable<Task<Result<TValue>>> resultTasks)

Parameters

resultTasks IEnumerable<Task<Result<TValue>>>

Returns

Task<Result<IEnumerable<TValue>>>

Deconstruct(out bool, out TValue?, out ImmutableList<IError>)

Deconstructs the result into success flag, value, and errors. Value is default when the result is failed.

public void Deconstruct(out bool isSuccess, out TValue? value, out ImmutableList<IError> errors)

Parameters

isSuccess bool
value TValue
errors ImmutableList<IError>

Examples

var (isSuccess, value, errors) = GetUser(id);
if (isSuccess) Console.WriteLine(value!.Name);

Deconstruct(out TValue?, out ImmutableList<IError>)

Deconstructs the result into value and errors. Value is default when the result is failed.

public void Deconstruct(out TValue? value, out ImmutableList<IError> errors)

Parameters

value TValue
errors ImmutableList<IError>

Examples

var (value, errors) = GetUser(id);
if (errors.Count == 0) Console.WriteLine(value!.Name);

Fail(IError)

Creates a failed Result<TValue> with an error reason.

public static Result<TValue> Fail(IError error)

Parameters

error IError

The error reason to include.

Returns

Result<TValue>

A failed Result<TValue> with the specified error reason.

Examples

var error = new ValidationError("Invalid email format");
var result = Result<User>.Fail(error);

Fail(IEnumerable<IError>)

Creates a failed Result<TValue> with multiple error reasons.

public static Result<TValue> Fail(IEnumerable<IError> errors)

Parameters

errors IEnumerable<IError>

Collection of error reasons.

Returns

Result<TValue>

A failed Result<TValue> with the specified error reasons.

Examples

var errors = new[] 
{ 
    new ValidationError("Name is required"), 
    new ValidationError("Email is invalid") 
};
var result = Result<User>.Fail(errors);

Fail(IEnumerable<string>)

Creates a failed Result<TValue> with multiple error messages.

public static Result<TValue> Fail(IEnumerable<string> messages)

Parameters

messages IEnumerable<string>

Collection of error messages.

Returns

Result<TValue>

A failed Result<TValue> with the specified error messages.

Examples

var errors = new[] { "Name is required", "Email is invalid" };
var result = Result<User>.Fail(errors);

Fail(string)

Creates a failed Result<TValue> with an error message.

public static Result<TValue> Fail(string message)

Parameters

message string

The error message to include.

Returns

Result<TValue>

A failed Result<TValue> with the specified error message.

Examples

var result = Result<User>.Fail("User not found");
Console.WriteLine(result.IsFailure); // true

FailIf(bool, IError, TValue)

Returns Fail if condition is true, otherwise Ok with error.

public static Result<TValue> FailIf(bool condition, IError error, TValue value)

Parameters

condition bool
error IError
value TValue

Returns

Result<TValue>

FailIf(bool, string, Func<TValue>)

Returns Fail if condition is true, otherwise Ok with lazy value.

public static Result<TValue> FailIf(bool condition, string errorMessage, Func<TValue> valueFactory)

Parameters

condition bool
errorMessage string
valueFactory Func<TValue>

Returns

Result<TValue>

FailIf(bool, string, TValue)

Returns Fail if condition is true, otherwise Ok with value.

public static Result<TValue> FailIf(bool condition, string errorMessage, TValue value)

Parameters

condition bool
errorMessage string
value TValue

Returns

Result<TValue>

FailIf(Func<bool>, string, Func<TValue>)

Evaluates both condition and value lazily.

public static Result<TValue> FailIf(Func<bool> predicate, string errorMessage, Func<TValue> valueFactory)

Parameters

predicate Func<bool>
errorMessage string
valueFactory Func<TValue>

Returns

Result<TValue>

FailIfAsync(Func<Task<bool>>, string, Func<Task<TValue>>)

Async version - evaluates both condition and value asynchronously.

public static Task<Result<TValue>> FailIfAsync(Func<Task<bool>> predicate, string errorMessage, Func<Task<TValue>> valueFactory)

Parameters

predicate Func<Task<bool>>
errorMessage string
valueFactory Func<Task<TValue>>

Returns

Task<Result<TValue>>

FromResult(Result)

Converts a non-generic failed Result to a generic Result<TValue>. Cannot be used with successful results - use Ok() methods instead.

public static Result<TValue> FromResult(Result result)

Parameters

result Result

The non-generic result to convert.

Returns

Result<TValue>

A failed Result<TValue> with the same reasons.

Examples

var nonGenericResult = Result.Fail("Operation failed");
var genericResult = Result<User>.FromResult(nonGenericResult);
// genericResult.IsFailure is true

Exceptions

InvalidOperationException

Thrown when the input result is successful.

GetValueOr(Func<ImmutableList<IError>, TValue>)

Gets the value if successful, otherwise computes a default based on the errors. Use this when you need error context to determine the fallback value.

public TValue GetValueOr(Func<ImmutableList<IError>, TValue> errorHandler)

Parameters

errorHandler Func<ImmutableList<IError>, TValue>

Function to compute default from errors.

Returns

TValue

The result value if successful, otherwise the error-based default.

Examples

var user = result.GetValueOr(errors => 
    new User { Name = $"Error: {errors[0].Message}" });

GetValueOr(Func<TValue>)

Gets the value if successful, otherwise computes a default value lazily. Use this when the default value is expensive to create.

public TValue GetValueOr(Func<TValue> defaultValueFactory)

Parameters

defaultValueFactory Func<TValue>

Function to compute the default value.

Returns

TValue

The result value if successful, otherwise the computed default.

Examples

var user = result.GetValueOr(() => _database.GetGuestUser());

GetValueOr(TValue)

Gets the value if successful, otherwise returns the specified default value. This is the recommended way to safely extract values without checking IsSuccess.

public TValue GetValueOr(TValue defaultValue)

Parameters

defaultValue TValue

The value to return if the result is failed.

Returns

TValue

The result value if successful, otherwise the default value.

Examples

var user = result.GetValueOr(new User { Name = "Guest" });
Console.WriteLine(user.Name);  // Safe - always has a value

LogOnFailure(ILogger, string)

Logs the result outcome only on failure and returns the result unchanged (Tap-style). Failure without an exception is logged at Warning; failure wrapping an ExceptionError at Error. On success, nothing is logged.

public Result<TValue> LogOnFailure(ILogger logger, string operationName)

Parameters

logger ILogger

The logger to write to.

operationName string

Name of the operation — appears in every log message.

Returns

Result<TValue>

The original result, unchanged.

Examples

Result<Order> result = await service.PlaceOrder(request)
    .LogOnFailure(logger, "PlaceOrder");

MapAsync<TOut>(Func<TValue, Task<TOut>>, CancellationToken)

Asynchronously transforms the value of a successful result using a mapper function. If the result is failed, returns a new failed result with the same reasons. If successful, preserves all success reasons from the original result.

public Task<Result<TOut>> MapAsync<TOut>(Func<TValue, Task<TOut>> mapper, CancellationToken cancellationToken = default)

Parameters

mapper Func<TValue, Task<TOut>>

The async function to convert the value.

cancellationToken CancellationToken

Optional cancellation token.

Returns

Task<Result<TOut>>

A task containing a new result with the transformed value or the original errors.

Type Parameters

TOut

The type of the output value.

Map<TOut>(Func<TValue, TOut>)

Transform the value of a successful result using a specific mapper function. If the result is failed, returns a new failed result with the same reasons. If successful, preserves all success reasons from the original result.

public Result<TOut> Map<TOut>(Func<TValue, TOut> mapper)

Parameters

mapper Func<TValue, TOut>

The function to convert the value.

Returns

Result<TOut>

A new result with the transformed value or the original errors.

Type Parameters

TOut

The type of the output value.

Ok(TValue)

Creates a successful result with a value.

public static Result<TValue> Ok(TValue value)

Parameters

value TValue

The value to wrap in a successful result.

Returns

Result<TValue>

A successful Result<TValue> containing the specified value.

Examples

var user = new User { Name = "John" };
var result = Result<User>.Ok(user);
Console.WriteLine(result.Value.Name); // John

Ok(TValue, ISuccess)

Creates a successful result with a value and success reason.

public static Result<TValue> Ok(TValue value, ISuccess success)

Parameters

value TValue

The value to wrap in a successful result.

success ISuccess

The success reason to include.

Returns

Result<TValue>

A successful Result<TValue> with the value and success reason.

Examples

var user = new User { Name = "John" };
var success = new Success("User created");
var result = Result<User>.Ok(user, success);

Ok(TValue, IEnumerable<string>)

Creates a successful result with a value and multiple success messages.

public static Result<TValue> Ok(TValue value, IEnumerable<string> messages)

Parameters

value TValue

The value to wrap in a successful result.

messages IEnumerable<string>

Collection of success messages.

Returns

Result<TValue>

A successful Result<TValue> with the value and messages.

Examples

var user = new User { Name = "John" };
var messages = new[] { "User created", "Profile completed" };
var result = Result<User>.Ok(user, messages);

Ok(TValue, ImmutableList<ISuccess>)

Creates a successful result with a value and multiple success reasons.

public static Result<TValue> Ok(TValue value, ImmutableList<ISuccess> successes)

Parameters

value TValue

The value to wrap in a successful result.

successes ImmutableList<ISuccess>

Collection of success reasons.

Returns

Result<TValue>

A successful Result<TValue> with the value and success reasons.

Examples

var user = new User { Name = "John" };
var successes = new[] 
{ 
    new Success("User created"), 
    new Success("Welcome email sent") 
};
var result = Result<User>.Ok(user, successes);

Ok(TValue, string)

Creates a successful result with a value and success message.

public static Result<TValue> Ok(TValue value, string message)

Parameters

value TValue

The value to wrap in a successful result.

message string

The success message to include.

Returns

Result<TValue>

A successful Result<TValue> with the value and message.

Examples

var user = new User { Name = "John" };
var result = Result<User>.Ok(user, "User created successfully");

OkIf(bool, Func<TValue>, string)

Evaluates value lazily - only creates value if condition is true. Useful when value creation is expensive.

public static Result<TValue> OkIf(bool condition, Func<TValue> valueFactory, string errorMessage)

Parameters

condition bool
valueFactory Func<TValue>
errorMessage string

Returns

Result<TValue>

OkIf(bool, TValue, IError)

Returns Ok with value if condition is true, otherwise Fail with error.

public static Result<TValue> OkIf(bool condition, TValue value, IError error)

Parameters

condition bool
value TValue
error IError

Returns

Result<TValue>

OkIf(bool, TValue, string)

Returns Ok with value if condition is true, otherwise Fail.

public static Result<TValue> OkIf(bool condition, TValue value, string errorMessage)

Parameters

condition bool
value TValue
errorMessage string

Returns

Result<TValue>

Examples

var result = Result<User>.OkIf(
    user != null, 
    user!, 
    "User not found"
);

OkIf(Func<bool>, Func<TValue>, string)

Evaluates both condition and value lazily.

public static Result<TValue> OkIf(Func<bool> predicate, Func<TValue> valueFactory, string errorMessage)

Parameters

predicate Func<bool>
valueFactory Func<TValue>
errorMessage string

Returns

Result<TValue>

OkIfAsync(bool, Func<Task<TValue>>, string)

Async version - creates value asynchronously if condition is true.

public static Task<Result<TValue>> OkIfAsync(bool condition, Func<Task<TValue>> valueFactory, string errorMessage)

Parameters

condition bool
valueFactory Func<Task<TValue>>
errorMessage string

Returns

Task<Result<TValue>>

OkIfAsync(Func<Task<bool>>, Func<Task<TValue>>, string)

Async version - evaluates both condition and value asynchronously.

public static Task<Result<TValue>> OkIfAsync(Func<Task<bool>> predicate, Func<Task<TValue>> valueFactory, string errorMessage)

Parameters

predicate Func<Task<bool>>
valueFactory Func<Task<TValue>>
errorMessage string

Returns

Task<Result<TValue>>

Recover(Func<ImmutableList<IError>, Result<TValue>>)

Recovers from a failure by invoking recover with the current errors. If the result is successful, it is returned unchanged.

public Result<TValue> Recover(Func<ImmutableList<IError>, Result<TValue>> recover)

Parameters

recover Func<ImmutableList<IError>, Result<TValue>>

Function that receives the current errors and returns a new result.

Returns

Result<TValue>

The original result if successful; otherwise the result of recover.

Examples

Result<User> result = await userRepository.GetAsync(id)
    .Recover(errors => userCache.Get(id));

RecoverAsync(Func<ImmutableList<IError>, Task<Result<TValue>>>, CancellationToken)

Asynchronously recovers from a failure by invoking recover with the current errors. If the result is successful, it is returned unchanged.

public Task<Result<TValue>> RecoverAsync(Func<ImmutableList<IError>, Task<Result<TValue>>> recover, CancellationToken cancellationToken = default)

Parameters

recover Func<ImmutableList<IError>, Task<Result<TValue>>>

Async function that receives the current errors and returns a new result.

cancellationToken CancellationToken

Optional cancellation token.

Returns

Task<Result<TValue>>

The original result if successful; otherwise the result of recover.

Tap(Action<TValue>)

Executes a side effect with the value without modifying the result. Useful for logging the value, telemetry, or other side effects that shouldn't affect the result flow.

public Result<TValue> Tap(Action<TValue> action)

Parameters

action Action<TValue>

The action to execute with the value if the result is successful.

Returns

Result<TValue>

The original result unchanged.

Examples

var result = Result<User>.Ok(user)
    .Tap(u => Console.WriteLine($"User created: {u.Name}"));

TapAsync(Func<TValue, Task>, CancellationToken)

Executes an async side effect with the value without modifying the result. Useful for async logging the value, telemetry, or other side effects that shouldn't affect the result flow.

public Task<Result<TValue>> TapAsync(Func<TValue, Task> action, CancellationToken cancellationToken = default)

Parameters

action Func<TValue, Task>

The async action to execute with the value if the result is successful.

cancellationToken CancellationToken

Optional cancellation token.

Returns

Task<Result<TValue>>

A task containing the original result unchanged.

Examples

var result = await Result<User>.Ok(user)
    .TapAsync(async u => await logger.LogAsync($"User created: {u.Name}"));

ToResult()

Converts this Result<TValue> to a non-generic Result, discarding the value. This is useful when you want to pass the result to methods that only care about success/failure. All reasons (successes and errors) are preserved.

public Result ToResult()

Returns

Result

A non-generic Result with the same reasons.

Examples

var userResult = Result<User>.Ok(user);
var result = userResult.ToResult();
// result.IsSuccess == true
// result contains the same reasons as userResult

ToString()

Returns a string representation of the Result including the value.

public override string ToString()

Returns

string

A string containing the result state and value information.

Examples

var result = Result<string>.Ok("Hello World");
Console.WriteLine(result.ToString());
// Output: Result: IsSuccess='True', Reasons=[], Value = Hello World

Try(Func<TValue>, Func<Exception, IError>?)

Executes an operation and wraps the result in a Result. If the operation throws an exception, returns a failed Result with an ExceptionError.

public static Result<TValue> Try(Func<TValue> operation, Func<Exception, IError>? errorHandler = null)

Parameters

operation Func<TValue>

The operation to execute that returns TValue.

errorHandler Func<Exception, IError>

Optional custom error handler. If null, creates an ExceptionError.

Returns

Result<TValue>

A successful Result with the operation's return value, or a failed Result with the error.

Examples

// Simple usage
var result = Result<int>.Try(() => int.Parse("42"));

// With custom error handler
var result = Result<User>.Try(
    () => GetUser(id),
    ex => new Error($"Failed to get user: {ex.Message}")
);

TryAsync(Func<Task<TValue>>, Func<Exception, IError>?, CancellationToken)

Asynchronously executes an operation and wraps the result in a Result. If the operation throws an exception, returns a failed Result with an ExceptionError.

public static Task<Result<TValue>> TryAsync(Func<Task<TValue>> operation, Func<Exception, IError>? errorHandler = null, CancellationToken cancellationToken = default)

Parameters

operation Func<Task<TValue>>

The async operation to execute that returns TValue.

errorHandler Func<Exception, IError>

Optional custom error handler. If null, creates an ExceptionError.

cancellationToken CancellationToken

Optional cancellation token.

Returns

Task<Result<TValue>>

A task containing a successful Result with the operation's return value, or a failed Result with the error.

Examples

var result = await Result<User>.TryAsync(
    async () => await GetUserAsync(id)
);

TryGetValue(out TValue)

Tries to get the value using the standard .NET try pattern. This is useful when you prefer the conventional TryGetValue pattern over GetValueOr.

public bool TryGetValue(out TValue value)

Parameters

value TValue

When this method returns, contains the value if the result is successful; otherwise, contains the default value.

Returns

bool

true if the result is successful and value was obtained; false if the result is failed.

Examples

if (result.TryGetValue(out var user))
{
    Console.WriteLine($"User: {user.Name}");
}
else
{
    Console.WriteLine("Operation failed");
}

WithActivity(Activity?)

Enriches an existing Activity span with Result outcome metadata. Sets result.outcome and, on failure, result.error.type, result.error.message, and optionally result.error.count (when there are multiple errors). Also updates Status to Ok or Error accordingly. The result is returned unchanged — this is a pure side-effect (Tap-style). Safe to call when activity is null — no-op in that case.

public Result<TValue> WithActivity(Activity? activity)

Parameters

activity Activity

The active span to enrich. Typically Current.

Returns

Result<TValue>

The original result, unchanged.

Examples

Result<User> result = await service.GetUser(id)
    .WithActivity(Activity.Current);

WithError(IError)

Adds an error reason to the result while preserving the value. Note: This will make the result failed if it wasn't already.

public Result<TValue> WithError(IError error)

Parameters

error IError

The error reason to add.

Returns

Result<TValue>

A new Result<TValue> with the added error reason.

Examples

var error = new Error("Database connection failed")
    .WithTag("Database", "Users");
var result = Result<User>.Ok(user).WithError(error);
// result.IsFailure will be true

WithError(string)

Adds an error reason with a message to the result while preserving the value. Note: This will make the result failed if it wasn't already.

public Result<TValue> WithError(string message)

Parameters

message string

The error message.

Returns

Result<TValue>

A new Result<TValue> with the added error reason.

Examples

var result = Result<User>.Ok(user)
    .WithError("User validation failed");
// result.IsFailure will be true

Exceptions

ArgumentException

Thrown when the message is null or empty.

WithErrors(IEnumerable<IError>)

Adds multiple error reasons to the result while preserving the value. Note: This will make the result failed if it wasn't already.

public Result<TValue> WithErrors(IEnumerable<IError> errors)

Parameters

errors IEnumerable<IError>

The error reasons to add.

Returns

Result<TValue>

A new Result<TValue> with the added error reasons.

Examples

var errors = new List<IError> 
{
    new Error("Invalid email"),
    new Error("Password too short")
};
var result = Result<User>.Ok(user).WithErrors(errors);
// result.IsFailure will be true

Exceptions

ArgumentException

Thrown when the errors list is empty.

WithLogger(ILogger, string)

Logs the result outcome to logger and returns the result unchanged (Tap-style). Success is logged at Debug; failure without an exception at Warning; failure wrapping an ExceptionError at Error.

public Result<TValue> WithLogger(ILogger logger, string operationName)

Parameters

logger ILogger

The logger to write to.

operationName string

Name of the operation — appears in every log message.

Returns

Result<TValue>

The original result, unchanged.

Examples

Result<User> result = await service.GetUser(id)
    .WithLogger(logger, "GetUser");

WithReason(IReason)

Adds a reason to the result while preserving the value.

public Result<TValue> WithReason(IReason reason)

Parameters

reason IReason

The reason to add.

Returns

Result<TValue>

A new Result<TValue> with the added reason.

Examples

var result = Result<User>.Ok(user)
    .WithReason(new Success("User created successfully"));

WithReasons(ImmutableList<IReason>)

Adds multiple reasons to the result while preserving the value.

public Result<TValue> WithReasons(ImmutableList<IReason> reasons)

Parameters

reasons ImmutableList<IReason>

The reasons to add.

Returns

Result<TValue>

A new Result<TValue> with the added reasons.

Examples

var reasons = new List<IReason> { new Success("Validated"), new Success("Processed") };
var result = Result<User>.Ok(user).WithReasons(reasons);

Exceptions

ArgumentException

Thrown when the reasons list is empty.

WithSuccess(ISuccess)

Adds a success reason to the result while preserving the value.

public Result<TValue> WithSuccess(ISuccess success)

Parameters

success ISuccess

The success reason to add.

Returns

Result<TValue>

A new Result<TValue> with the added success reason.

Examples

var success = new Success("Operation completed").WithTag("UserId", user.Id);
var result = Result<User>.Ok(user).WithSuccess(success);

WithSuccess(string)

Adds a success reason with a message to the result while preserving the value.

public Result<TValue> WithSuccess(string message)

Parameters

message string

The success message.

Returns

Result<TValue>

A new Result<TValue> with the added success reason.

Examples

var result = Result<User>.Ok(user)
    .WithSuccess("User profile updated successfully");

Exceptions

ArgumentException

Thrown when the message is null or empty.

WithSuccesses(IEnumerable<ISuccess>)

Adds multiple success reasons to the result while preserving the value.

public Result<TValue> WithSuccesses(IEnumerable<ISuccess> successes)

Parameters

successes IEnumerable<ISuccess>

The success reasons to add.

Returns

Result<TValue>

A new Result<TValue> with the added success reasons.

Examples

var successes = new List<ISuccess> 
{
    new Success("Validated"),
    new Success("Processed"),
    new Success("Saved")
};
var result = Result<User>.Ok(user).WithSuccesses(successes);

Exceptions

ArgumentException

Thrown when the successes list is empty.

Operators

implicit operator Result<TValue>(Error)

Implicitly converts an Error to a failed Result. Throws for null input to fail fast for programmer errors.

public static implicit operator Result<TValue>(Error error)

Parameters

error Error

Returns

Result<TValue>

implicit operator Result<TValue>(Error[])

Implicitly converts an array of Errors to a failed Result. Throws for null input to fail fast for programmer errors. Returns a ConversionError if the array is empty.

public static implicit operator Result<TValue>(Error[] errors)

Parameters

errors Error[]

Returns

Result<TValue>

implicit operator Result<TValue>(ExceptionError)

Implicitly converts an ExceptionError to a failed Result. Throws for null input to fail fast for programmer errors.

public static implicit operator Result<TValue>(ExceptionError error)

Parameters

error ExceptionError

Returns

Result<TValue>

implicit operator Result<TValue>(ExceptionError[])

Implicitly converts an array of ExceptionErrors to a failed Result. Throws for null input to fail fast for programmer errors. Returns a ConversionError if the array is empty.

public static implicit operator Result<TValue>(ExceptionError[] errors)

Parameters

errors ExceptionError[]

Returns

Result<TValue>

implicit operator Result<TValue>(List<Error>)

Implicitly converts a List of Errors to a failed Result. Throws for null input to fail fast for programmer errors. Returns a ConversionError if the list is empty.

public static implicit operator Result<TValue>(List<Error> errors)

Parameters

errors List<Error>

Returns

Result<TValue>

implicit operator Result<TValue>(List<ExceptionError>)

Implicitly converts a List of ExceptionErrors to a failed Result. Throws for null input to fail fast for programmer errors. Returns a ConversionError if the list is empty.

public static implicit operator Result<TValue>(List<ExceptionError> errors)

Parameters

errors List<ExceptionError>

Returns

Result<TValue>

implicit operator Result<TValue>(TValue)

Implicitly converts a value to a successful Result.

public static implicit operator Result<TValue>(TValue value)

Parameters

value TValue

Returns

Result<TValue>