BooleanExt
Extension Method to Execute Delegate Based on Boolean Value
Source
static class BooleanExt
{
public delegate void delExecuteMethod();
/// <summary>
///
/// </summary>
/// <param name="value">Current value of Boolean</param>
/// <param name="executeWhen">Value of Boolean when to execute delegate.</param>
/// <param name="executeMethod">Delegate method to execute.</param>
public static void When(this bool value, bool executeWhen, delExecuteMethod executeMethod)
{
if (value == executeWhen)
executeMethod.Invoke();
}
/// <summary>
/// Executes delegate when the boolean value is true.
/// </summary>
/// <param name="value">Current value of the boolean.</param>
/// <param name="executeMothod">Delegate method to execute.</param>
public static void WhenTrue(this bool value, delExecuteMethod executeMothod)
{
if (value)
executeMothod.Invoke();
}
/// <summary>
/// Executes the delegate when the boolean value is false.
/// </summary>
/// <param name="value">Current value of the boolean.</param>
/// <param name="executeMothod">Delegate method to execute.</param>
public static void WhenFalse(this bool value, delExecuteMethod executeMothod)
{
if (!value)
executeMothod.Invoke();
}
}
Example
BooleanExt.delExecuteMethod d = delegate () { Console.WriteLine("TaDa"); };
bool state = true;
// Should execute delegate
state.When(true, d);
// Should not execute delegate
state.When(false, d);
state = false;
// Should execute delegate
state.When(false, d);
// Should not execute delegate
state.When(true, d);
state = true;
// Should execute delegate
state.WhenTrue(d);
// Should not execute delegate
state.WhenFalse(d);
state = false;
// Should not execute delegate
state.WhenTrue(d);
// Should execute delegate
state.WhenFalse(d);