using System; namespace Umbraco.Core { /// /// Represents the result of an operation attempt. /// /// The type of the attempted operation result. [Serializable] public struct Attempt { // 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; } /// /// Gets the attempt result, if successful, else a default value. /// public TResult ResultOr(TResult value) => Success ? Result : value; // optimize, use a singleton failed attempt private static readonly Attempt Failed = new Attempt(false, default(TResult), null); /// /// Creates a successful attempt. /// /// The successful attempt. public static Attempt Succeed() { return new Attempt(true, default(TResult), null); } /// /// Creates a successful attempt with a result. /// /// The result of the attempt. /// The successful attempt. public static Attempt Succeed(TResult result) { return new Attempt(true, result, null); } /// /// Creates a failed attempt. /// /// The failed attempt. public static Attempt Fail() { return 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) { return new Attempt(false, default(TResult), exception); } /// /// Creates a failed attempt with a result. /// /// The result of the attempt. /// The failed attempt. public static Attempt Fail(TResult result) { return new Attempt(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) { return new Attempt(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) { return condition ? new Attempt(true, default(TResult), 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) { return new Attempt(condition, result, null); } /// /// Implicitly operator to check if the attempt was successful without having to access the 'success' property /// /// /// public static implicit operator bool(Attempt a) { return a.Success; } } }