namespace Umbraco.Cms.Core;
///
/// Represents the result of an operation attempt.
///
/// The type of the attempted operation result.
[Serializable]
public struct Attempt
{
// optimize, use a singleton failed attempt
private static readonly Attempt Failed = new(false, default, null);
// private - use Succeed() or Fail() methods to create attempts
private Attempt(bool success, TResult? result, Exception? exception)
{
Success = success;
Result = result;
Exception = exception;
}
///
/// Gets a value indicating whether this was successful.
///
public bool Success { get; }
///
/// Gets the exception associated with an unsuccessful attempt.
///
public Exception? Exception { get; }
///
/// Gets the attempt result.
///
public TResult? Result { get; }
///
/// Implicitly operator to check if the attempt was successful without having to access the 'success' property
///
///
///
public static implicit operator bool(Attempt a) => a.Success;
///
/// Gets the attempt result, if successful, else a default value.
///
public TResult ResultOr(TResult value)
{
if (Success && Result is not null)
{
return Result;
}
return value;
}
///
/// Creates a successful attempt.
///
/// The successful attempt.
public static Attempt Succeed() => new(true, default, null);
///
/// Creates a successful attempt with a result.
///
/// The result of the attempt.
/// The successful attempt.
public static Attempt Succeed(TResult? result) => new(true, result, null);
///
/// Creates a failed attempt.
///
/// The failed attempt.
public static Attempt Fail() => Failed;
///
/// Creates a failed attempt with an exception.
///
/// The exception causing the failure of the attempt.
/// The failed attempt.
public static Attempt Fail(Exception? exception) => new(false, default, exception);
///
/// Creates a failed attempt with a result.
///
/// The result of the attempt.
/// The failed attempt.
public static Attempt Fail(TResult result) => new(false, result, null);
///
/// Creates a failed attempt with a result and an exception.
///
/// The result of the attempt.
/// The exception causing the failure of the attempt.
/// The failed attempt.
public static Attempt Fail(TResult result, Exception exception) => new(false, result, exception);
///
/// Creates a successful or a failed attempt.
///
/// A value indicating whether the attempt is successful.
/// The attempt.
public static Attempt If(bool condition) => condition ? new Attempt(true, default, null) : Failed;
///
/// Creates a successful or a failed attempt, with a result.
///
/// A value indicating whether the attempt is successful.
/// The result of the attempt.
/// The attempt.
public static Attempt If(bool condition, TResult? result) => new(condition, result, null);
}