using System;
using Umbraco.Core.Dynamics;
namespace Umbraco.Core
{
///
/// Represents the result of an operation attempt.
///
/// The type of the attempted operation result.
[Serializable]
public struct Attempt
{
private readonly bool _success;
private readonly T _result;
private readonly Exception _exception;
///
/// Gets a value indicating whether this was successful.
///
public bool Success
{
get { return _success; }
}
///
/// Gets the exception associated with an unsuccessful attempt.
///
public Exception Exception { get { return _exception; } }
///
/// Gets the attempt result.
///
public T Result
{
get { return _result; }
}
// optimize, use a singleton failed attempt
private static readonly Attempt Failed = new Attempt(false, default(T), null);
// private - use Succ() or Fail() methods to create attempts
private Attempt(bool success, T result, Exception exception)
{
_success = success;
_result = result;
_exception = exception;
}
///
/// Creates a successful attempt.
///
/// The successful attempt.
public static Attempt Succ()
{
return new Attempt(true, default(T), null);
}
///
/// Creates a successful attempt with a result.
///
/// The result of the attempt.
/// The successful attempt.
public static Attempt Succ(T 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(T), exception);
}
///
/// Creates a failed attempt with a result.
///
/// The result of the attempt.
/// The failed attempt.
public static Attempt Fail(T 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(T 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 success)
{
return success ? new Attempt(true, default(T), 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 success, T result)
{
return new Attempt(success, result, null);
}
}
}