Thursday, 15 August 2013

Inner Workings of the IF() Function - Why Aren't Expressions Evaluated?

Inner Workings of the IF() Function - Why Aren't Expressions Evaluated?

Short version
How does the IF() Function cause the passed expressions to NOT be
evaluated prior to being passed in as Parameters?
Detailed Version
I am part of a Standards committee, and a discussion was initiated which,
in general, is trying to Ban The use of the IIF() Function. The general
consensus is that if you want to do a short line-length assignment IF() is
okay. And if you for some reason want to evaluate two expressions, don't
try to accomplish that all on one line, explicitly and purposefully
evaluate the expressions on seperate lines, then do an IF() call with the
results in the If True and If Else Parameters.
I'm Asserting that before a Function(param1, expression) is stepped into,
any expressions are evaluated. Then, their evaluated value is passed as a
Parameter.
That being asserted, this makes sense:
Sub Main()
Dim intTest As Integer = 0
Dim blnResult As Boolean = IIf(2 = 2, Integer.TryParse("3", intTest),
Integer.TryParse("4", intTest))
'intTest = 4
End Sub
As expected, blnResult is True.
Because the conditional of the IIF() Function is True, the value of the
expression in the "If True" Parameter is the resulting assignment.
But BOTH the If True AND If Else expressions were evaluated (in written
order) prior to even stepping into the IIF() Function, so intTest became
4.
As far as I'm concerned, that is programatically expected, but not the
results desired.
On the reverse side of the coin, we have this:
Sub Main()
Dim intTest As Integer = 0
Dim blnResult As Boolean = If(2 = 2, Integer.TryParse("3", intTest),
Integer.TryParse("4", intTest))
'intTest = 3
End Sub
As the inverse of the previous issue, we now have:
As expected, blnResult is True.
Because the conditional of the IF() Function is True, the value of the
expression in the "If True" Parameter is the resulting assignment.
But ONLY the If True (in this case) is evaluated, so intTest became 3.
As far as I'm concerned, that is the results desired, but not
programatically expected.
I'd like to see a custom function that does the same thing as IF()

No comments:

Post a Comment