This a simple C# class libary to handle error of an operation.
Operation Result can be used for error handling without throwing costly Exceptions.
The purpose of the Operation Result design pattern is to give an operation (a method) the possibility to return a complex result (an object), allowing the consumer to:
- Access the result of an operation; in case there is one.
- Access the success indicator of an operation.
- Access the cause of the failure in case the operation was not successful.
Represents the result of an operation. The result must be immutable and its properties must be read-only.
public struct Resultpublic struct Result<T>Access the result of the operation, in case there is one.
public T Value { get; set; }Access the success indicator of the operation.
public bool IsSuccess { get; }Access the cause of the failure in case the operation was not successful.
public Exception Exception { get; }public static Result Success()
=> new Result(true);public static Result<T> Success<T>(T value)
=> new Result<T>(value);public static Result Error(Exception exception)
=> new Result(exception);public static Result<T> Error<T>(Exception exception)
=> new Result<T>(exception);public static implicit operator Result<T>(T value)
=> new Result<T>(value);
public static implicit operator Result<T>(Exception exception)
=> new Result<T>(exception);The following example demonstrates how to use it:
Result<int> IncrementOne(int value)
{
if (value > 9)
{
return new ArgumentOutOfRangeException(nameof(value), "Value cannot be greater than nine.");
}
return value++;
}public void Deconstruct(out bool success, out T value)
{
success = IsSuccess;
value = Value;
}
public void Deconstruct(out bool success, out T value, out Exception exception)
{
success = IsSuccess;
value = Value;
exception = Exception;
}The following example demonstrates how to use it:
public static void Main()
{
var (isSuccess, value, exception) = IncrementOne(2);
// Do something with the data.
}