We can use the If operator instead of If...Then...Else..End If statement blocks.
Consider the following example:
is the same as
If() uses short-circuit evaluation, which means that it will only evaluate the arguments it uses. If the condition is false (or a
Nullable that is
Nothing), the first alternative will not be evaluated at all, and none of its side effects will be observed. This is effectively the same as C#'s ternary operator in the form of
This is especially useful in avoiding exceptions:
We all know that dividing by zero will throw an exception, but
If() here guards against this by short-circuiting to only the expression that the condition has already ensured is valid.
varString <> "N/A" evaluates to
False, it will assign
varDate's value as
Now.Date without evaluating the first expression.
Older versions of VB do not have the
If() operator and have to make do with the
IIf() built-in function. As it's a function, not an operator, it does not short-circuit; all expressions are evaluated, with all possible side-effects, including performance penalties, changing state, and throwing exceptions. (Both of the above examples that avoid exceptions would throw if converted to
IIf.) If any of these side effects present a problem, there's no way to use an inline conditional; instead, rely on
If..Then blocks as usual.