You can actually. You can use (extension) methods like this:
// For first case.
public static void If(this Lazy<bool>[] checks, Predicate<Lazy<bool>[]> ifCondition, Action<Lazy<bool>[]> ifAction) {
if (ifCondition(checks)) ifAction(checks);
}
// For second case.
public static void If(this object[] variables, Predicate<object[]> ifCondition, Action<object[]> ifAction) {
if (ifCondition(variables)) ifAction(variables);
}
And use of it would look like this:
// First case.
new[] { new Lazy<bool>(() => foo == true), new Lazy<bool>(() => bar == false) }.
If(checks => checks[0].Value || checks[1].Value, checks => {
if (checks[0].Value) {
//foo is true
}
if (!checks[1].Value) {
//bar is false
}
});
// Second case.
new[] { "bar" }.If(variables => (string)variables[0] == "bar", variables => {
//we now have the runtime generated variable.
});
This will limit the scope of those temporary values. However, this does not provide any check for whether you actually using checks
or variables
in the right way. And it would be harder to debug if something goes wrong then simple if
statement.
This could also be extended to accept Func
instead of Action
that your If
method could return
result as well. And it is possible to even add ElseIf
and Else
methods to chain with If
method (to mimic all if
statement behavior).