Tag: If operator

Conditional short-circuit evaluation

I am a long time Visual Basic developer, and I have been using the IIf function for as long as I can remember, when I needed inline evaluation of an expression.

Check out this expression.

Dim expressionResult As Integer = IIf(Not controller Is Nothing, controller.Value, 10)

When using the IIf function, bot the True part of the evaluation, controller.Value, and the False part, 10, are evaluated, no matter what the result of the expression, Not controller Is Nothing. In the case shown, when controller is null, the IIf function will throw an exception, because the True part cannot be evaluated due to controller being null. Fear not, and this is the surprising bit that has eluded me for quite some time; you can just use the “new” If operator with short-circuit evaluation, like this:

Dim expressionResult As Integer = If(Not controller Is Nothing, controller.Value, 10)

This will always return a value. Really simple, isn’t it, and so much easier to read than that comparable and IMHO silly Visual C# notation.

——————————————————– UPDATE ——————————————————–

I just looked closer at the documentation for the If operator, and there’s an overload that take only two arguments; This means that the first argument, shown in the previous example can be omitted. The first argument is evaluated and returned to the caller, unless it evaluates to Nothing. If it evaluates to Nothing, the second argument is returned.

Dim expressionResult As Object = If(controller, otherController)
Advertisements