Skip to content

Result<T>

Class public
Encapsulates the outcome of a domain operation as either a success carrying a value of type T, or a failure carrying an error message.
Namespace SampleApi
Assembly SampleApi
Package v1.0.0.0
public class Result<T>
T
T
The type of the value returned on success.
Result`1 implements the discriminated-result pattern: callers inspect IsSuccess (or IsFailure) before accessing Value or Error. Accessing Value on a failed result returns default for T. Prefer the static factory methods Ok(`0) and String) over direct construction to ensure the success/error invariants are satisfied. This type can be used as a method return value in service layers to avoid throwing exceptions for expected failure conditions.
Error Section titled Error nullable
string?
string? Result<T>.Error

Gets the error message describing why the operation failed.

bool Result<T>.IsFailure

Gets a value indicating whether the operation failed.

bool Result<T>.IsSuccess

Gets a value indicating whether the operation succeeded.

Value Section titled Value nullable
T?
T? Result<T>.Value

Gets the value produced by a successful operation.

Result<T> Result<T>.Fail(
string error)

Creates a failed result with the specified error message.

error string
A message describing the failure.
Result<T> A Result`1 representing a failed outcome.
Result<T> Result<T>.Ok(
T value)

Creates a successful result containing the specified value.

value T
The success value.
Result<T> A Result`1 representing a successful outcome.

Using Result to handle success and failure paths:

Result<Customer> result = await customerService.TryFindAsync(id);
if (result.IsSuccess)
{
Console.WriteLine($"Found: {result.Value!.FullName}");
}
else
{
Console.WriteLine($"Error: {result.Error}");
}

Returning a Result from a service method:

public Result<Customer> Validate(Customer customer)
{
if (string.IsNullOrWhiteSpace(customer.FullName))
return Result<Customer>.Fail("Full name is required.");
return Result<Customer>.Ok(customer);
}