Coding For a Living

rss

A place to share and comment about coding for a living.


Visual Basic If Operator Mike McIntyre

It looks like a function but it is an operator.  The Visual Basic If operator provides the functionality of the IIF function and more - including short-circuiting. It can be use as a ternary operator which mimics the functionality of the IIF function while adding some more to it, and as a binary operator which provides a comparison/assignment feature. image

The operator uses short-circuit evaluation to conditionally return one of two values. The If operator can be called with three arguments or with two arguments.

When If is called by using three arguments, the first argument must evaluate to a value that can be cast as a Boolean. That Boolean value will determine which of the other two arguments is evaluated and returned.

' This statement prints TruePart, because the first argument is true. Console.WriteLine(If(True, "TruePart", "FalsePart")) ' This statement prints FalsePart, because the first argument is false. Console.WriteLine(If(False, "TruePart", "FalsePart")) Dim number = 3 ' With number set to 3, this statement prints Positive. Console.WriteLine(If(number >= 0, "Positive", "Negative")) number = -1 ' With number set to -1, this statement prints Negative. Console.WriteLine(If(number >= 0, "Positive", "Negative"))



Comments are closed.
Showing 0 Comment