Result<T> Struct
Definition
Represents the outcome of an operation that produces a value: either Success(value) carrying a non-null
value of type T, or Failure(error) carrying a ResultError.
public readonly struct Result<T> : IEquatable<Result<T>>
Type Parameters
TThe type of the value carried on success.
- Implements
-
IEquatable<Result<T>>
- Inherited Members
- Extension Methods
Remarks
Result<T> makes failure explicit in a signature without resorting to exceptions for expected error
paths. Chain transformations with Map<TResult>(Func<T, TResult>) and
Bind<TResult>(Func<T, Result<TResult>>) - the error propagates untouched past every combinator - and
collapse to a final value with Match<TResult>(Func<T, TResult>, Func<ResultError, TResult>) or the
GetValueOrDefault overloads. Instances are created through the factories on the non-generic
Result type: Success<T>(T) and Failure<T>(ResultError).
default(Result<T>) equals a failure carrying an empty ResultError - a result that was
never assigned behaves exactly like an explicit failure, so the type is total and safe to use as a field or array
element without initialization. Error on default(Result<T>) is valid and returns the
empty error.
Properties
Error
Gets the error carried by a failed result.
public ResultError Error { get; }
Property Value
- ResultError
The ResultError describing the failure.
Remarks
Prefer TryGetError(out ResultError) or
Match<TResult>(Func<T, TResult>, Func<ResultError, TResult>) over direct access when success is
an expected state; Error is intended for call sites that have already established
IsFailure. On default(Result<T>) it is valid and returns the empty error.
Exceptions
- InvalidOperationException
The result does not represent a failure.
IsFailure
Gets a value indicating whether this result represents failure.
public bool IsFailure { get; }
Property Value
IsSuccess
Gets a value indicating whether this result represents success.
public bool IsSuccess { get; }
Property Value
Value
Gets the value carried by a successful result.
public T Value { get; }
Property Value
- T
The value carried by this result.
Remarks
Prefer TryGetValue(out T),
Match<TResult>(Func<T, TResult>, Func<ResultError, TResult>), or the GetValueOrDefault
overloads over direct access when failure is an expected state; Value is intended for call sites
that have already established IsSuccess.
Exceptions
- InvalidOperationException
The result does not represent a success.
Methods
Bind<TResult>(Func<T, Result<TResult>>)
Projects the carried value into another result using the specified result-returning selector.
public Result<TResult> Bind<TResult>(Func<T, Result<TResult>> selector)
Parameters
Returns
- Result<TResult>
The result produced by the selector when this result represents success; otherwise a failure carrying the original error.
Type Parameters
TResultThe value type of the resulting result.
Remarks
The selector is not invoked when this result is a failure.
Exceptions
- ArgumentNullException
selectoris null.
Equals(Result<T>)
Determines whether the specified result is equal to the current instance.
public bool Equals(Result<T> other)
Parameters
otherResult<T>The result to compare with this instance.
Returns
- bool
true if both are successes carrying values that compare equal using Default, or both are failures whose errors compare equal using Equals(ResultError); otherwise, false.
Equals(object?)
Determines whether the specified object is equal to the current result.
public override bool Equals(object? obj)
Parameters
objobjectThe object to compare. Only another Result<T> can be equal; all other types, including null, return false.
Returns
Filter(Func<T, bool>, ResultError)
Demotes a success to a failure carrying the specified error when the carried value does not satisfy the specified predicate.
public Result<T> Filter(Func<T, bool> predicate, ResultError error)
Parameters
predicateFunc<T, bool>The condition the carried value must satisfy.
errorResultErrorThe error carried by the failure produced when the predicate is not satisfied.
Returns
- Result<T>
This result when it is already a failure or when a value is present and satisfies
predicate; otherwise a failure carryingerror.
Remarks
The predicate is not invoked when this result is already a failure; the original error is preserved unchanged.
This is the failure-shaped counterpart of Filter(Func<T, bool>), which drops a filtered
value to None: here the caller names the error that the filtered-out value represents.
Exceptions
- ArgumentNullException
predicateis null.
Filter(Func<T, bool>, Func<T, ResultError>)
Demotes a success to a failure carrying an error produced by the specified factory when the carried value does not satisfy the specified predicate.
public Result<T> Filter(Func<T, bool> predicate, Func<T, ResultError> errorFactory)
Parameters
predicateFunc<T, bool>The condition the carried value must satisfy.
errorFactoryFunc<T, ResultError>The factory invoked with the carried value to produce the error when the predicate is not satisfied.
Returns
- Result<T>
This result when it is already a failure or when a value is present and satisfies
predicate; otherwise a failure carryingerrorFactory(value).
Remarks
Neither the predicate nor the factory is invoked when this result is already a failure; the original error is preserved unchanged. The factory is invoked only for a present value that fails the predicate, so the error can describe the specific value that was rejected.
Exceptions
- ArgumentNullException
predicateorerrorFactoryis null.
GetHashCode()
Returns a hash code for the current instance consistent with Equals(Result<T>).
public override int GetHashCode()
Returns
- int
The carried value's hash code for success; otherwise the error's hash code.
GetValueOrDefault()
Returns the carried value, or the default value of T when the result represents failure.
public T? GetValueOrDefault()
Returns
- T
The carried value, or
default(T).
GetValueOrDefault(Func<T>)
Returns the carried value, or the value produced by the specified factory when the result represents failure.
public T GetValueOrDefault(Func<T> defaultFactory)
Parameters
defaultFactoryFunc<T>The factory invoked to produce the fallback value.
Returns
- T
The carried value, or the factory's result.
Remarks
The factory is not invoked when the result represents success.
Exceptions
- ArgumentNullException
defaultFactoryis null.
GetValueOrDefault(T)
Returns the carried value, or the specified fallback when the result represents failure.
public T GetValueOrDefault(T defaultValue)
Parameters
defaultValueTThe value returned when the result represents failure.
Returns
- T
The carried value, or
defaultValue.
GetValueOrThrow()
Returns the carried value, or throws when the result represents failure.
public T GetValueOrThrow()
Returns
- T
The carried value.
Remarks
The captured Exception is never rethrown directly - doing so would corrupt its original stack trace. It is exposed as the inner exception of the thrown InvalidOperationException instead.
Exceptions
- InvalidOperationException
The result represents failure. The exception message is the error's Message when non-empty; otherwise a generic not-a-success message. The error's Exception, when present, is attached as the InnerException.
MapError(Func<ResultError, ResultError>)
Transforms the error carried by a failed result using the specified selector.
public Result<T> MapError(Func<ResultError, ResultError> selector)
Parameters
selectorFunc<ResultError, ResultError>The transformation applied to the carried error.
Returns
- Result<T>
A failure carrying
selector(error)when this result represents failure; otherwise this result unchanged.
Remarks
The selector is not invoked when this result is a success.
Exceptions
- ArgumentNullException
selectoris null.
Map<TResult>(Func<T, TResult>)
Projects the carried value into a new result using the specified selector.
public Result<TResult> Map<TResult>(Func<T, TResult> selector)
Parameters
selectorFunc<T, TResult>The projection applied to the carried value.
Returns
- Result<TResult>
Success(selector(value))when the result represents success; otherwise a failure carrying the original error.
Type Parameters
TResultThe type produced by the selector.
Examples
var length = Result.Success("railway").Map(s => s.Length); // Success(7)
var failed = Result.Failure<string>("boom").Map(s => s.Length); // Failure(boom) - selector not invoked
Remarks
The selector is not invoked when this result is a failure. The projected value is lifted through the strict Success<T>(T) factory, so a null projection result throws ArgumentNullException - a successful result can never carry null.
Exceptions
Match(Action<T>, Action<ResultError>)
Invokes the matching action for the state of the result.
public void Match(Action<T> onSuccess, Action<ResultError> onFailure)
Parameters
onSuccessAction<T>The action invoked with the carried value when the result represents success.
onFailureAction<ResultError>The action invoked with the carried error when the result represents failure.
Exceptions
- ArgumentNullException
onSuccessoronFailureis null.
Match<TResult>(Func<T, TResult>, Func<ResultError, TResult>)
Collapses the result to a single value by invoking the matching branch.
public TResult Match<TResult>(Func<T, TResult> onSuccess, Func<ResultError, TResult> onFailure)
Parameters
onSuccessFunc<T, TResult>The projection invoked with the carried value when the result represents success.
onFailureFunc<ResultError, TResult>The projection invoked with the carried error when the result represents failure.
Returns
- TResult
The value produced by the invoked branch.
Type Parameters
TResultThe type produced by both branches.
Examples
var label = result.Match(v => $"got {v}", error => $"failed: {error}");
Exceptions
- ArgumentNullException
onSuccessoronFailureis null.
Tap(Action<T>)
Invokes the specified action with the carried value when the result represents success.
public Result<T> Tap(Action<T> action)
Parameters
actionAction<T>The side effect invoked with the carried value.
Returns
- Result<T>
This result, unchanged, so calls can be chained.
Remarks
The action is not invoked when this result is a failure; the result itself is always returned.
Exceptions
- ArgumentNullException
actionis null.
TapError(Action<ResultError>)
Invokes the specified action with the carried error when the result represents failure.
public Result<T> TapError(Action<ResultError> action)
Parameters
actionAction<ResultError>The side effect invoked with the carried error.
Returns
- Result<T>
This result, unchanged, so calls can be chained.
Remarks
The action is not invoked when this result is a success; the result itself is always returned.
Exceptions
- ArgumentNullException
actionis null.
ToOption()
Converts the result to an option, discarding the error.
public Option<T> ToOption()
Returns
- Option<T>
Some(value)when the result represents success; otherwiseNone.
Remarks
This is the inverse of ToResult(ResultError), except that the error is lost - convert back requires supplying a new error.
ToString()
Returns a string representation of the result.
public override string ToString()
Returns
- string
"Success(value)"for success; otherwise"Failure(error)".
TryGetError(out ResultError)
Attempts to retrieve the error carried by a failed result.
public bool TryGetError(out ResultError error)
Parameters
errorResultErrorWhen this method returns, the error if the result represents failure; otherwise the default error.
Returns
TryGetValue(out T)
Attempts to retrieve the value carried by a successful result.
public bool TryGetValue(out T value)
Parameters
valueTWhen this method returns, the value if the result represents success; otherwise the default value.
Returns
Operators
operator ==(Result<T>, Result<T>)
Determines whether two results are equal.
public static bool operator ==(Result<T> left, Result<T> right)
Parameters
Returns
operator !=(Result<T>, Result<T>)
Determines whether two results are not equal.
public static bool operator !=(Result<T> left, Result<T> right)
Parameters
Returns
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |