using System;
using Chernobyl.Values;
namespace Chernobyl.Conversion
{
///
/// Converts a bool to a specified value depending on whether it is true or
/// false. This type can be implicitly converted to a
/// which is the method to use for bool conversion.
///
/// The type of the conversion.
public class ConvertBool
{
///
/// Initializes a new instance of the
/// class.
///
/// The value to convert to when a bool is true.
/// The value to convert to when a bool is false.
public ConvertBool(TTo trueValue, TTo falseValue)
{
_trueValue = trueValue;
_falseValue = falseValue;
}
///
/// Implicitly converets from to
/// . Use this implicit conversion to
/// get the method that handles the conversion.
///
/// The instance that is to be converted to the
/// .
/// The result of the conversion.
public static implicit operator Func(ConvertBool converter)
{
return converter.Convert;
}
///
/// The method that converts the bool to the value requested.
///
/// The bool to convert.
/// The value of the bool
TTo Convert(bool value)
{
return value ? _trueValue : _falseValue;
}
///
/// The converted value of the bool when it is true.
///
readonly TTo _trueValue;
///
/// The converted value of the bool when it is false.
///
readonly TTo _falseValue;
}
///
/// Utility and extensions methods for
/// and its dependencies.
///
public static class ConvertBoolExtensions
{
///
/// Returns an that holds and maintains a
/// converted version of a that contains a bool.
///
/// The type to convert the bool to.
/// The instance whose contained bool is to be
/// converted.
/// The value to convert to when a bool is true.
/// The value to convert to when a bool is false.
/// The which holds and maintains the
/// converted value.
public static IValue Convert(
this IValue value, TTo trueValue, TTo falseValue)
{
return new FromSourceConversion(value, new ConvertBool(trueValue, falseValue));
}
}
}